Linux一对一通信(UDP)
客户端:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/socket.h>
#include <sys/socket.h>
#include<string.h>
#include <arpa/inet.h>
#define MAX_BUF_SIZE 1024
#define PORT 8888
int main()
{
int sockfd, addrlen, n;
char buffer[MAX_BUF_SIZE];
struct sockaddr_in addr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
{
fprintf(stderr, "socket falied\n");
exit(EXIT_FAILURE);
}
addrlen = sizeof(struct sockaddr_in);
bzero(&addr, addrlen);
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
puts("socket success");
while(1)
{
bzero(buffer, MAX_BUF_SIZE);
fgets(buffer, MAX_BUF_SIZE, stdin);
sendto(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)(&addr), addrlen);
printf("client send msg is %s\n", buffer);
n = recvfrom(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)(&addr), &addrlen);
fprintf(stdout, "clinet Receive message from server is %s\n", buffer);
}
close(sockfd);
exit(0);
return 0;
}
服务端:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#define PORT 8888
#define MAX_MSG_SIZE 1024
int main()
{
int sockfd, addrlen, n;
struct sockaddr_in addr;
char msg[MAX_MSG_SIZE];
sockfd = socket(AF_INET, SOCK_DGRAM, 0); //数据报
if (sockfd < 0)
{
fprintf(stderr, "socket failed\n");
exit(EXIT_FAILURE);
}
addrlen = sizeof(struct sockaddr_in);
bzero(&addr, addrlen); //清空addr
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(PORT);
if (bind(sockfd, (struct sockaddr*)(&addr), addrlen) < 0)
{
fprintf(stderr, "bind fail\n");
exit(EXIT_FAILURE);
}
puts("bind success");
while (1)
{
bzero(msg, MAX_MSG_SIZE); //清空数组
n = recvfrom(sockfd, msg, sizeof(msg), 0, (struct sockaddr *)(&addr), &addrlen);
fprintf(stdout, "Recevie message from client is %s\n", msg);
fgets(msg, MAX_MSG_SIZE,stdin);
printf("Server endpoint input message %s\n", msg);
sendto(sockfd, msg, n, 0,(struct sockaddr *)(&addr), addrlen);
}
close(sockfd);
exit(EXIT_SUCCESS);
}
技术不分国界