#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <errno.h>
#define SERVER_PORT 8888
#define MAX_MSG_SIZE 1024
/*******************************************************************************************
Function:
Description:
*******************************************************************************************/
void udps_respon(int sockfd)
{
struct sockaddr_in addr;
int addrlen,rx_length;
char msg[MAX_MSG_SIZE];
while(1)
{
// 从网络上读, 并写到网络上
bzero(msg,MAX_MSG_SIZE);
addrlen = sizeof(struct sockaddr);
// 从客户端接收数据
fprintf(stdout,"Server is waitting for data!\n");
rx_length = recvfrom(sockfd,msg,MAX_MSG_SIZE,0,(struct sockaddr*)&addr,&addrlen);
msg[rx_length] = '\0';
// 打印消息提示:服务器已经收到消息
fprintf(stdout,"Server has received data:%s",msg);
}
}
/*******************************************************************************************
Function:
Description:
The functionality of socket()
int socket(int domain, int type, int protocol);
@domain - selects the protocol family
val:
AF_UNIX, AF_LOCAL Local communication unix(7)
AF_INET IPv4 Internet protocols ip(7)
AF_INET6 IPv6 Internet protocols ipv6(7)
AF_IPX IPX - Novell protocols
AF_NETLINK Kernel user interface device netlink(7)
AF_X25 ITU-T X.25 / ISO-8208 protocol x25(7)
AF_AX25 Amateur radio AX.25 protocol
AF_ATMPVC Access to raw ATM PVCs
AF_APPLETALK Appletalk ddp(7)
AF_PACKET Low level packet interface packet(7)
@type - specifies the communication semantics
val:
SOCK_STREAM sequenced, reliable, two-way, connection-based byte streams.
SOCK_DGRAM connectionless, unreliable messages
SOCK_SEQPACKET sequenced, reliable, two-way connection-based data
SOCK_RAW raw network protocol access.
SOCK_RDM reliable datagram layer that does not guar‐antee ordering.
SOCK_PACKET Obsolete and should not be used in new programs;
@protocol - specify the index of particular protocol,which will take place of domain.
Normally it can be specified as 0.
*******************************************************************************************/
int main(int args,char *argv[])
{
int sockfd;
struct sockaddr_in server_addr; // IP data structure
// 服务器端开始建立sockfd描述符
if( (sockfd=socket(AF_INET,SOCK_DGRAM,0))==-1 ) // 使用UDP协议
{
fprintf(stderr,"Socket error:%s\n\a",strerror(errno));
exit(1);
}
// 服务器端填充 sockaddr 结构体
bzero(&server_addr,sizeof(struct sockaddr_in)); // 数据清0
server_addr.sin_family = AF_INET; // IP协议
server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // 接收来本机所有网卡(所有IP)的数据
server_addr.sin_port = htons(SERVER_PORT); // 转换端口号
// 绑定IP地址和端口到socket
if( bind(sockfd,(struct sockaddr *)(&server_addr), sizeof(struct sockaddr_in))<0 )
{
fprintf(stderr,"Bind error:%s\n\a",strerror(errno));
}
else
{
fprintf(stdout,"Server bind socket successfully!\n");
}
// 进行读写操作
udps_respon(sockfd);
// 关闭连接
close(sockfd);
// 循环下一个
//return(0);
}