我绑定到内核模块中的socket。我从另一个套接字获得字符串格式的IP。我应该如何将此IP传递给htonl()。我尝试将其类型转换为(long int)。但是,显然它不起作用。
如何实现这一目标?
答案 0 :(得分:4)
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);
答案 1 :(得分:3)
哟可以使用这样的东西:
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);
答案 2 :(得分:0)
来自Beej's Guide to Network Programming
inet_addr()以in_addr_t的形式返回地址,如果有错误,则返回-1。 (这与尝试转换字符串“ 255.255.255.255”(这是一个有效的IP地址)的结果相同。这就是为什么inet_aton()更好。)
示例:
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");