linux实现udp
linux实现udp
前言:udp通信需指定自己的接收端口和IP地址,并且有至少两个线程,即发送和接收。
话不多说,看代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <arpa/inet.h>
#include <pthread.h>
//发送信息线程
void *sendMsg(int to_port){
//创建套接字
int read_fd = socket(AF_INET, SOCK_DGRAM, 0);
if(read_fd == -1){
perror("socket error");
exit(1);
}
struct sockaddr_in to;
memset(&to, 0, sizeof (to));
to.sin_family = AF_INET;
to.sin_port = htons(to_port);
inet_pton(AF_INET, "127.0.0.1", &to.sin_addr.s_addr);
printf("sendMsg:%d\n",to_port);
while(1){
//数据发送
char buf[1024] = {0};
fgets(buf, sizeof (buf), stdin);
sendto(read_fd, buf, strlen(buf)+1, 0, (struct sockaddr*)&to, sizeof (to));
printf("I say: %s\n", buf);
}
close(read_fd);
}
//接收信息线程
void *recieveMsg(int recieve_port){
int write_fd = socket(AF_INET, SOCK_DGRAM, 0);
if(write_fd == -1){
perror("socket error");
exit(1);
}
printf("recieveMsg:%d\n",recieve_port);
struct sockaddr_in I;
memset(&I, 0, sizeof (I));
I.sin_family = AF_INET;
I.sin_port = htons(recieve_port);
I.sin_addr.s_addr = htonl(INADDR_ANY);
int ret = bind(write_fd, (struct sockaddr*)&I, sizeof (I));
if(ret == -1){
perror("bind error");
exit(1);
}
char buf[1024] = {0};
struct sockaddr_in client;
socklen_t cli_len = sizeof (client);
while(1){
int recvlen = recvfrom(write_fd, buf, sizeof (buf), 0, (struct sockaddr*)&client, &cli_len);
if(recvlen == -1){
perror("recvfrom error");
exit(1);
}
printf("he say: %s", buf);
}
close(write_fd);
}
int main(int argc, const char* argv[]){
if(argc != 3){
printf("Usage : ./client <recieve port> <sendto port>\n");
return 0;
}
printf("recieve_port:%s++++++++to_port:%s\n",argv[1],argv[2]);
pthread_t send_id, recieve_id;
pthread_create(&send_id, NULL, sendMsg, atoi(argv[2]));
pthread_create(&recieve_id, NULL, recieveMsg, atoi(argv[1]));
pthread_join(send_id,NULL);
pthread_join(recieve_id,NULL);
return 0;
}
运行结果:
小白一个,还望各位大神指教。