server-api-inet_aton

原型

inet_aton() converts the Internet host address cp from the IPv4 numbers-and-dots notation into binary form (in network byte order) and stores it in the structure that inp points to.

将网络地址转成网络二进制的数字然后存于参数inp所指的in_addr结构中。

函数原型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// cp
// a.b.c.d Each of the four numeric parts specifies a byte of the address; the bytes are assigned in left-to-right order to produce the binary address.
// a.b.c Parts a and b specify the first two bytes of the binary address. Part c is inter‐preted as a 16-bit value that defines the rightmost two bytes of the binary address.This notation is suitable for specifying (outmoded) Class B network addresses.
// a.b Part a specifies the first byte of the binary address. Part b is interpreted as a 24-bit value that defines the rightmost three bytes of the binary address. This notation is suitable for specifying (outmoded) Class C network addresses.
// a The value a is interpreted as a 32-bit value that is stored directly into the binary address without any byte rearrangement.
// 要转换的ip地址
// inp
// 用于接收转换后的网络二进制的地址
//
// return:
// returns nonzero if the address is valid, zero if not.
// 成功则返回非0值,失败则返回0。
//
//
int inet_aton(const char *cp, struct in_addr *inp);

使用参考

支持一个客户端的回射服务器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>

#include<stdlib.h>
#include<stdio.h>
#include<errno.h>
#include<string.h>

#define ERR_EXIT(m)\
do\
{\
perror(m); \
exit(EXIT_FAILURE); \
}while (0)

int main(void)
{
int listenfd;
/*if ((listenfd = socket(PF_INET, SOCK_STREAM, 0))<0)*/
if ((listenfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
ERR_EXIT("socket");

struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(5188);
inet_aton("127.0.0.1", &servaddr.sin_addr);
// servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
// servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");

int on = 1;
if(setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
ERR_EXIT("SETSOCKOPT") ;

if (bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
ERR_EXIT("BIND");

if (listen(listenfd, SOMAXCONN) < 0)
ERR_EXIT("LISTEN");

struct sockaddr_in peeraddr;
socklen_t peerlen = sizeof(peeraddr);
int conn;
if ((conn = accept(listenfd, (struct sockaddr*)&peeraddr, &peerlen)) < 0)
ERR_EXIT("ACCEPT");

printf("ip=%s port=%d\n", inet_ntoa(peeraddr.sin_addr), ntohs(peeraddr.sin_port));

char recvbuf[1024];
while (1)
{
memset(recvbuf, 0, sizeof(recvbuf));
int ret = read(conn, recvbuf, sizeof(recvbuf));
fputs(recvbuf, stdout);
write(conn, recvbuf, ret);
}

close(conn);
close(listenfd) ;

return 0;
}