Reputation: 385
I am binding to socket in a kernel module. I get the IP in string format from another socket. How should I pass this IP to htonl(). I tried typecasting it to (long int). But, obviously it won't work.
How to achieve this?
Upvotes: 1
Views: 11404
Reputation: 862
From Beej's Guide to Network Programming
inet_addr() returns the address as an in_addr_t, or -1 if there's an error. (That is the same result as if you tried to convert the string "255.255.255.255", which is a valid IP address. This is why inet_aton() is better.)
Example:
struct sockaddr_in antelope;
char *some_addr;
inet_aton("10.0.0.1", &antelope.sin_addr); // store IP in antelope
some_addr = inet_ntoa(antelope.sin_addr); // return the IP
printf("%s\n", some_addr); // prints "10.0.0.1"
// and this call is the same as the inet_aton() call, above:
antelope.sin_addr.s_addr = inet_addr("10.0.0.1");
Upvotes: 0
Reputation: 11453
unsigned int inet_addr(char *str)
{
int a, b, c, d;
char arr[4];
sscanf(str, "%d.%d.%d.%d", &a, &b, &c, &d);
arr[0] = a; arr[1] = b; arr[2] = c; arr[3] = d;
return *(unsigned int *)arr;
}
//use it as follows:
//inet_addr() returns address in Network Byte Order, so no need of htonl()
thesockaddr_in.sin_addr.s_addr = inet_addr(str);
Upvotes: 4
Reputation: 219
Yo can use something like this:
const char *IP = "62.4.36.125";
SOCKADDR_IN DestAddr;
DestAddr.sin_family = AF_INET;
DestAddr.sin_port = htons (PORTNUM);
DestAddr.sin_addr.s_addr = inet_addr(IP);
Upvotes: 3