一、socket 网络套接字
1
2
3
4
5
6
7
8
9
10
11
12
13
|
struct
sockaddr_in
{
short
sin_family;
/*Address family一般来说AF_INET(地址族)PF_INET(协议族)*/
unsigned
short
sin_port;
/*Port number(必须要采用网络数据格式,普通数字可以用htons()函数转换成网络数据格式的数字)*/
struct
in_addr sin_addr;
/*IP address in network byte order(Internet address)*/
unsigned
char
sin_zero[8];
/*Same size as struct sockaddr没有实际意义,只是为了 跟SOCKADDR结构在内存中对齐*/
};
|
1
2
3
4
5
|
typedef
uint32_t in_addr_t;
struct
in_addr
{
in_addr_t s_addr;
};
|
三、绑定
四、接收
五、发送
服务器端代码:
#include
#include
#include
#include
#include
#include
#include
int main(int argc,char *argv[])
{
if(argc!=3)
{
printf("Usage ./server [ip] [port]\n");
return 1;
}
int sock=socket(AF_INET,SOCK_DGRAM,0);
if(sock<0)
{
perror("socket");
return 2;
}
struct sockaddr_in local;
local.sin_family=AF_INET;//ipv4
local.sin_port=htons(atoi(argv[2]));//主机字节序转换为网络字节序
local.sin_addr.s_addr=inet_addr(argv[1]);//字符串转in_addr的函数
if(bind(sock,(struct sockaddr*)&local,sizeof(local))<0)
{
perror("bind");
return 3;
}
char buf[1024];
struct sockaddr_in client;
while(1)
{
socklen_t len=sizeof(client);
ssize_t s=recvfrom(sock,buf,sizeof(buf)-1,0,(struct sockaddr*)&client,&len);
if(s>0)
{
buf[s]=0;
printf("[%s:%d]:%s\n",inet_ntoa(client.sin_addr),\
ntohs(client.sin_port),buf);
sendto(sock,buf,strlen(buf),0, \
(struct sockaddr*)&client,sizeof(client));
}
}
close(sock);
return 0;
}
客户端的代码:
#include
#include
#include
#include
#include
#include
#include
int main(int argc,char *argv[])
{
if(argc!=3)
{
printf("./Usage [ip] [port]\n");
return 1;
}
int sock=socket(AF_INET,SOCK_DGRAM,0);
if(sock<0)
{
perror("socket");
return 2;
}
struct sockaddr_in server;
server.sin_family=AF_INET;
server.sin_port=htons(atoi(argv[2]));
server.sin_addr.s_addr=inet_addr(argv[1]);
char buf[1024];
struct sockaddr_in peer;
while(1)
{
socklen_t len=sizeof(peer);
printf("Please Enter# ");
fflush(stdout);
ssize_t s=read(0,buf,sizeof(buf)-1);
if(s>0)
{
buf[s-1]=0;
sendto(sock,buf,strlen(buf),0,\
(struct sockaddr*)&server,sizeof(server));
ssize_t _s=recvfrom(sock,buf,sizeof(buf)-1,0,\
(struct sockaddr*)&peer,&len);
}
UDP是无连接的,面向数据报,不可靠的传输协议。