development

문자열을 IP 주소로 또는 그 반대로 변환하는 방법

big-blog 2020. 11. 7. 10:49
반응형

문자열을 IP 주소로 또는 그 반대로 변환하는 방법


문자열 ipAddress (struct in_addr) 및 그 반대로 변환하려면 어떻게해야합니까? 서명되지 않은 긴 ipAddress를 어떻게 제출합니까? 감사


다른 방법으로 필요한 경우 inet_ntop()사용하십시오 inet_pton(). inet_ntoa(), inet_aton()더 이상 사용되지 않으며 ipv6를 지원 하지 않으므로 사용하지 마십시오 .

여기 에 꽤 많은 예제 가있는 멋진 가이드 가 있습니다.

// IPv4 demo of inet_ntop() and inet_pton()

struct sockaddr_in sa;
char str[INET_ADDRSTRLEN];

// store this IP address in sa:
inet_pton(AF_INET, "192.0.2.33", &(sa.sin_addr));

// now get it back and print it
inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN);

printf("%s\n", str); // prints "192.0.2.33"

이 코드를 사용하여 문자열을 DWORD로 다시 변환 할 수있었습니다.

char strAddr[] = "127.0.0.1"
DWORD ip = inet_addr(strAddr); // ip contains 16777343 [0x0100007f in hex]

struct in_addr paddr;
paddr.S_un.S_addr = ip;

char *strAdd2 = inet_ntoa(paddr); // strAdd2 contains the same string as strAdd

이전 MFC 코드의 유지 관리 프로젝트에서 작업 중이므로 사용되지 않는 함수 호출을 변환 할 수 없습니다.


inet_ntoa()a in_addr를 문자열 로 변환 합니다.

inet_ntoa 함수는 (Ipv4) 인터넷 네트워크 주소를 인터넷 표준 점 분리 10 진수 형식의 ASCII 문자열로 변환합니다.

inet_addr() 반대로 일을한다

inet_addr 함수는 IPv4 점으로 구분 된 십진수 주소를 포함하는 문자열을 IN_ADDR 구조에 적합한 주소로 변환합니다.

PS 이것은 "in_addr to string"을 검색하는 첫 번째 결과입니다!


질문을 제대로 이해했는지 잘 모르겠습니다.

어쨌든, 당신은 이것을 찾고 있습니까?

std::string ip ="192.168.1.54";
std::stringstream s(ip);
int a,b,c,d; //to store the 4 ints
char ch; //to temporarily store the '.'
s >> a >> ch >> b >> ch >> c >> ch >> d;
std::cout << a << "  " << b << "  " << c << "  "<< d;

산출:

192  168  1  54

문자열을 in-addr로 변환하려면 :

in_addr maskAddr;
inet_aton(netMaskStr, &maskAddr);

in_addr을 문자열로 변환하려면 :

char saddr[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &inaddr, saddr, INET_ADDRSTRLEN);

이 예는 문자열에서 ip로 또는 그 반대로 변환하는 방법을 보여줍니다.

struct sockaddr_in sa;
char ip_saver[INET_ADDRSTRLEN];

// store this IP address in sa:
inet_pton(AF_INET, "192.0.1.10", &(sa.sin_addr));

// now get it back 
sprintf(ip_saver, "%s", sa.sin_addr));

// prints "192.0.2.10"
printf("%s\n", ip_saver); 

세 번째 inet_pton매개 변수는 in_addr구조에 대한 포인터 입니다. inet_pton호출 이 성공 하면 in_addr구조가 주소 정보로 채워집니다. 구조의 S_addr필드에는 네트워크 바이트 순서 (역순)의 IP 주소가 포함됩니다.


다음은 uint32_t 네이티브 엔디안을 문자열로, 문자열을 네이티브 엔디안 uint32_t로 변환하는 사용하기 쉽고 스레드로부터 안전한 C ++ 함수입니다.

#include <arpa/inet.h> // inet_ntop & inet_pton
#include <string.h> // strerror_r
#include <arpa/inet.h> // ntohl & htonl
using namespace std; // im lazy

string ipv4_int_to_string(uint32_t in, bool *const success = nullptr)
{
    string ret(INET_ADDRSTRLEN, '\0');
    in = htonl(in);
    const bool _success = (NULL != inet_ntop(AF_INET, &in, &ret[0], ret.size()));
    if (success)
    {
        *success = _success;
    }
    if (_success)
    {
        ret.pop_back(); // remove null-terminator required by inet_ntop
    }
    else if (!success)
    {
        char buf[200] = {0};
        strerror_r(errno, buf, sizeof(buf));
        throw std::runtime_error(string("error converting ipv4 int to string ") + to_string(errno) + string(": ") + string(buf));
    }
    return ret;
}
// return is native-endian
// when an error occurs: if success ptr is given, it's set to false, otherwise a std::runtime_error is thrown.
uint32_t ipv4_string_to_int(const string &in, bool *const success = nullptr)
{
    uint32_t ret;
    const bool _success = (1 == inet_pton(AF_INET, in.c_str(), &ret));
    ret = ntohl(ret);
    if (success)
    {
        *success = _success;
    }
    else if (!_success)
    {
        char buf[200] = {0};
        strerror_r(errno, buf, sizeof(buf));
        throw std::runtime_error(string("error converting ipv4 string to int ") + to_string(errno) + string(": ") + string(buf));
    }
    return ret;
}

fair warning, as of writing, they're un-tested. but these functions are exactly what i was looking for when i came to this thread.


Hexadecimal IP Address to String IP

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    uint32_t ip = 0x0AA40001;
    string ip_str="";
    int temp = 0;
    for (int i = 0; i < 8; i++){
        if (i % 2 == 0)
        {
            temp += ip & 15;
            ip = ip >> 4;
        }
        else
        {
            stringstream ss;
            temp += (ip & 15) * 16;
            ip = ip >> 4;
            ss << temp;
            ip_str = ss.str()+"." + ip_str;
            temp = 0;
        }
    }
    ip_str.pop_back();
    cout << ip_str;
}

Output:10.164.0.1

참고URL : https://stackoverflow.com/questions/5328070/how-to-convert-string-to-ip-address-and-vice-versa

반응형