1.pton
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <arpa/inet.h>
int main() { char* addr = "192.168.1.2"; int buf[4]; inet_pton(AF_INET,addr,(void*)&buf); unsigned char *p = (unsigned char*)buf; printf("%d %d %d %d\n",p[0],p[1],p[2],p[3]); return 0; }
|
1 2 3 4 5 6 7
| #include <arpe/inet.h>
int inet_pton(int family, const char *strptr, void *addrptr); 返回值:若成功则为1,若输入不是有效的表达式则为0,若出错则为-1
const char * inet_ntop(int family, const void *addrptr, char *strptr, size_t len); 返回值:若成功则为指向结构的指针,若出错则为NULL
|
(1)这两个函数的family参数既可以是AF_INET(ipv4)也可以是AF_INET6(ipv6)。如果,以不被支持的地址族作为family参数,这两个函数都返回一个错误,并将errno置为EAFNOSUPPORT.
(2)第一个函数尝试转换由strptr指针所指向的字符串,并通过addrptr指针存放二进制结果,若成功则返回值为1,否则如果所指定的family而言输入字符串不是有效的表达式格式,那么返回值为0.
(3)inet_ntop进行相反的转换,从数值格式(addrptr)转换到表达式(strptr)。inet_ntop函数的strptr参数不可以是一个空指针。调用者必须为目标存储单元分配内存并指定其大小,调用成功时,这个指针就是该函数的返回值。len参数是目标存储单元的大小,以免该函数溢出其调用者的缓冲区。如果len太小,不足以容纳表达式结果,那么返回一个空指针,并置为errno为ENOSPC。
https://blog.csdn.net/zyy617532750/article/details/58595700/
inet_pton()和inet_ntop()函数详解
2.客户端连接
1.创建套接字socket
2.连接connect
3.读写
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
| #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <arpa/inet.h>
int main() { int sock_fd = socket(AF_INET,SOCK_STREAM,0); if(sock_fd == -1){ printf("socket failed..\n"); return 1; } struct sockaddr_in addr_in; addr_in.sin_family = AF_INET; addr_in.sin_port= htons(8080); inet_pton(AF_INET,"172.22.203.74",&addr_in.sin_addr.s_addr); connect(sock_fd,(struct sockaddr*)&addr_in,sizeof(addr_in)); char buf[1024]=""; while(1){ int n = read(0,buf,sizeof(buf)); write(sock_fd,buf,n); n = read(sock_fd,buf,sizeof(buf)); write(1,buf,n); }
return 0; }
|
3.服务端连接
1.创建套接字socket
2.绑定bind
3.侦听listen
4.接受,创建新的文件描述符accept
5.读写
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
| #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <arpa/inet.h>
int main() { int sock_fd; sock_fd = socket(AF_INET,SOCK_STREAM,0); if(sock_fd==-1){ printf("socket failed..\n"); return 1; } struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(8000); addr.sin_addr.s_addr = 0; bind(sock_fd,(struct sockaddr *)&addr,sizeof(addr)); listen(sock_fd,128); struct sockaddr_in client; socklen_t len = sizeof(client); int new_sock_fd = accept(sock_fd,(struct sockaddr*)&client,&len);
char buf[1024] = ""; while(1){ write(new_sock_fd,"haha",4); printf("Success.\n"); } close(sock_fd); close(new_sock_fd);
return 0; }
|