Reputation: 67
my goal is to successfully call the function inet_pton
in C.
I am using Windows 7. So far I learned that inet_pton
has 3 arguments. Besides, its job is to translate human IP representation into binary representation for the computer.
Details on my understanding of the arguments of inet_pton(a,b,c)
:
a
: An address_family. For example AF_INET
b
: A pointer to the human readable representation of the IP address (e.g."127.0.0.1").
c
: A pointer to the "thing" where the translated IP address (binary form) is stored.
In a tutorial I read it is said inet_pton
will store the translation inside the array c points to.
This page
https://msdn.microsoft.com/de-de/library/windows/desktop/cc805844(v=vs.85).aspx
tells me, that the third argument has the type PVOID
.
INT WSAAPI inet_pton(__in INT Family,__in PCTSTR pszAddrString,__out PVOID pAddrBuf);
In my opinion the receiving array should be an char array. But PVOID
is not equal to char.
The last idea I have is that a cast is involved, though I am only familiar with a cast in a situation like
buffer = (char*) malloc (i+1);
At the moment my code Looks like this:
#include <stdio.h>
#include <stdlib.h>
#include<stdio.h>
#include <windows.h>
#include <Winsock2.h>
#include <Ws2tcpip.h>
int main(int argc, char *argv[])
{
char *ptr2="127.0.0.1";
char buffe[512];
PVOID *ptr3;
PVOID ptr3=&buffe;
inet_pton(AF_INET,ptr2,ptr3);
system("PAUSE");
return 0;
}
How can I initialize the 3rd argument correctly (if it's necessary)? How to deal with the fact that the array storing the binary representation of the IP address should have the type char while the pointer should have the type PVOID
?
My compiler is complaining about conflicting types for ptr3. Thank you so much for your help.
Upvotes: 0
Views: 1303
Reputation: 19760
PVOID
is a typedef for void *
which means that the third argument expects a generic pointer. PCTSTR
is ultimately typedefed to either const char *
(if UNICODE
is not defined) or const wchar_t *
(if UNICODE
is defined). See Windows Data Types for more information on those specific types.
Instead of trying to figure out how many bytes to allocate using malloc()
(hint: sizeof(IN_ADDR)
), you can just directly use the data type it expects: IN_ADDR. According to the documentation, the third argument pAddrBuf
needs to be large enough to hold an IN_ADDR
when the first argument Family
is AF_INET
.
Try doing something like this:
#include <WinDef.h>
#include <Winsock2.h>
#include <Ws2tcpip.h>
int main(int argc, char *argv[]) {
char ip_string[] = "127.0.0.1";
IN_ADDR ip_value;
inet_pton(AF_INET, ip_string, &ip_value);
system("PAUSE");
return 0;
}
Upvotes: 1