cwindowswinapiwinsockwinsock2

Invalid IP address with InetPton() function


I am using the Windows OS and am coding in C, currently.

I am a complete beginner in socket programming, and have this following piece of code that is returning unwanted values. (MAXLINE = 4096), and I have CTR_SECURITY... defined.

const char* IPADDRESS = "xxx.xxx.xx.xx";//IP address

int sockFileDescriptor = 0, n;
int sendbytes = 0;
SOCKADDR_IN servaddr = { 0 };

char sendl[MAXLINE];
char recvl[MAXLINE];
memset(sendl, 0, MAXLINE);

WSADATA wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);

if (0 > (sockFileDescriptor = socket(AF_INET, SOCK_STREAM, 0))) { 
    printf("no socket"); 
    exit(-1); 
}

memset((char*)&servaddr, 0, sizeof(servaddr));

servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(1337);

int a = InetPton(AF_INET, IPADDRESS, &servaddr.sin_addr.S_un.S_addr);
if (0 >= a) {
    printf("inetPton %d, returnV = %d", WSAGetLastError(), a);
    exit(-1);
}

if (0 > connect(sockFileDescriptor, (SOCKADDR*)&servaddr, sizeof(servaddr))) {
    printf("connect wrong %d", WSAGetLastError());
    exit(-1);
}
sprintf(sendl, "GET / HTTP/1.1\r\n\r\n");

sendbytes = strlen(sendl);
/*
if (_write(sockFileDescriptor, sendl, sendbytes) != sendbytes) {
    printf("error");
    exit(-1);
}*/

if (0 > send(sockFileDescriptor, sendl, strlen(sendl), 0)) {
    printf("sendGoneWrong");
    exit(-1);
}

memset(recvl, 0, MAXLINE);
while ((n = _read(sockFileDescriptor, recvl, MAXLINE - 1))>0) {
    printf("%s", recvl);
}
exit(0);

It returns "inetPton 10022, returnV = 0".

I have tried other IP addresses, but none of them changed the result, making me believe I am not using the InetPton() function correctly.

By the way, in InetPton(), should I be using servAddr.sin_addr or servaddr.sin_addr.S_un.S_addr?


Solution

  • Wrong string type. IPADDRESS is a pointer of PCWSTR type. So you should use PCWSTR or const wchar_t* to define IPADDRESS.

    Check the doc: https://learn.microsoft.com/en-us/windows/win32/learnwin32/working-with-strings enter image description here

    After modifying that, you can go to next step. enter image description here