程序说明:用linuxc网络编程的UDP套接字编程,实现内网中不同ip之间服务端和客户端的双向通信
Service端:
#include
#include
#include
#include
#include
#include
#include
#define PORTNO 60000
#define PORTS 56666
#define MSGSIZE 128
int main( void )
{
int sfd,ret,len,sfd1;
struct sockaddr_in st, cst;
char msg[MSGSIZE];
len = sizeof(struct sockaddr);
sfd = socket( AF_INET, SOCK_DGRAM, 0);
memset( &st, 0x0, len );
st.sin_family = AF_INET; //IPV4协议族
st.sin_addr.s_addr = inet_addr("192.168.36.129");
st.sin_port = htons(PORTNO);
ret = bind( sfd, (struct sockaddr *)&st, len );
len = sizeof(struct sockaddr);
sfd1 = socket( AF_INET, SOCK_DGRAM, 0);
memset( &cst, 0x0, len );
cst.sin_family = AF_INET; //IPV4协议族
cst.sin_addr.s_addr = inet_addr("192.168.36.129");//ip地址
cst.sin_port = htons(PORTS); //设定端口号
//接受客户端的数据
while(1){
ret = recvfrom( sfd, msg, MSGSIZE, 0, (struct sockaddr *)&st, (socklen_t *)&len );
msg[ret]=0x0;
printf("服务器从客户端接收的数据为:[%s]\n", msg);
//发送服务端的数据
char BUFF;
scanf("%s",&BUFF);
strcpy(msg,&BUFF);
sendto( sfd1, msg, strlen(msg),0, (struct sockaddr *)&cst, (socklen_t)len );
}
return 0;
}
client端:
#include
#include
#include
#include
#include
#include
#include
#define PORTNO 60000
#define PORTS 56666
#define MSGSIZE 128
int main( void )
{
int sfd,sfd1,ret,ret1;
struct sockaddr_in st,cst;
size_t len;
char msg[MSGSIZE];
len = sizeof(struct sockaddr);
sfd = socket( AF_INET, SOCK_DGRAM, 0);
memset( &st, 0x0, len );
st.sin_family = AF_INET; //IPV4协议族
st.sin_addr.s_addr = inet_addr("192.168.36.129");
st.sin_port = htons(PORTNO); //设定端口号
len = sizeof(struct sockaddr);
sfd1 = socket( AF_INET, SOCK_DGRAM, 0);
memset( &cst, 0x0, len );
cst.sin_family = AF_INET; //IPV4协议族
cst.sin_addr.s_addr = inet_addr("192.168.36.129");
cst.sin_port = htons(PORTS);
ret = bind( sfd1, (struct sockaddr *)&cst, len );
char BUFF;
while(1){
scanf("%s",&BUFF);
strcpy(msg,&BUFF);
sendto( sfd, msg, strlen(msg),0, (struct sockaddr *)&st, (socklen_t)len );
ret = recvfrom( sfd1, msg, MSGSIZE, 0, (struct sockaddr *)&cst, (socklen_t *)&len );
msg[ret]=0x0;
printf("服务器从客户端接收的数据为:[%s]\n", msg);
}
return 0;
}
只做记录学习
(qq:九七二四三九三二九,有不懂的可以问我,一起学习)