数据存储优先顺序转换
1 2 3 4 5 6
| #include<arpa/inet.h> uint16_t htons(uint16_t hostshort); uint32_t htonl(uint32_t hostlong); uint16_t ntohs(uint16_t netshort); uint32_t ntohl(uint32_t netlong);
|
#地址格式转换 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> int inet_aton(const char *srraddr,struct in_addr *addrptr);
char *inet_ntoa(struct in_addr inaddr);
in_addr_t inet_addr(const char *straddr);
const chat* inet_pton(int family,const char *src,char *dst,socklen_t len);
int inet_pton(int family,const char *src,void *dst);
|
# TCP 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
|
#include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> #include<unistd.h> #include<string.h> #include<stdio.h> #include<stdlib.h> int socketFd=socket(AF_INET,SOCKSTREAM,0);
struct sockaddr_in serAddr; memset(&serAddr,0,sizeof(serAddr); serAddr.sin_family=AF_INET; serAddr.sin_port=htons(atoi(port)); serAddr.sin_addr.s_addr=inet_addr(ip); int resuce=1; setsockopt(socketFd,SOL_SOCKET,SO_REUSEADDR,&resue,sizeof(int)); bind(socketFd,(struct sockaddr*)&serAddr,sizeof(struct sockaddr); listen(socketFd,10);
recv(socketFd,&buf,sizeof(buf),0);
send(int s,const void *msg,int len,unsigned int flags);
close(int fd);
|
1 2 3 4 5 6 7 8
| struct sockaddr_in { usigned short int sin_family; uint16_t sin_port; struct in_addr sin_addr; unsigned char sin_zero[8]; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| int connect(int sockfd,struct sockaddr *ser_addr,int addrlen);
struct sockaddr_in seraddr; memset(&seraddr,0,sizeof(struct sockaddr); seraddr.sin_family=AF_INET: seraddr.sin_port=htons(2345); seraddr.sin_addr.s_addr=inet_addr(ip); if(connect(sfd,(struct sockaddr*)&seraddr,sizeof(struct sockaddr))==-1){ perror("connect"); close(sfd); exit(-1); }
|
#UDP 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
| int main() { int sfd=socket(AF_INET<SOCK_DGRAM,0); if(-1==sfd) { perror("socket"); exit(-1); } struct sockaddr_in saddr; bzero(&saddr,sizeof(saddr)); saddr.sin_family=AF_INET; saddr.sin_port=htons(2345); saddr.sin_addr.s_addr=INADDR_ANY; if(bind(sfd,(struct sockaddr*)&saddr,sizeof(struct sockaddr))==-1) { perror("bind"); close(sfd); exit(-1); } char buf[512]={0}; while(1) { struct sockaddr_in fromaddr; bzero(&fromaddr,sizeof(fromaddr)); int fromaddrlen=sizeof(struct sockaddr); if(recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&fromaddr,&fromaddrlen)==-1) { perror("recvfrom); close(sfd); exit(-1); } printf("receive from %s:%d,the message is %s\n",inet_ntoa(fromaddr.sin_addr),ntohs(fromaddr.sin_port),buf); sendto(sfd,"world",6,0,(struct sockaddr*)&fromaddr,sizeof(struct sockaddr)); } close(sfd); }
|