服务器端
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#define ERR_MSG(msg) \
do { \
fprintf(stderr, "line : %d\n", __LINE__); \
perror(msg); \
} while (0)
#define IP "192.168.0.122"
#define PORT 8888
int main(int argc, char const* argv[])
{
// 1.创建报式套接字
int sfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sfd < 0) {
ERR_MSG("socket error");
return -1;
}
printf("socket successful __%d__\n", __LINE__);
// 2.绑定服务器IP地址和端口
// 2.1 填充地址信息结构体
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
sin.sin_addr.s_addr = inet_addr(IP);
// 2.2 绑定(必须)
if (bind(sfd, (struct sockaddr*)&sin, sizeof(sin)) < 0) {
ERR_MSG("bind error");
return -1;
}
char buf[128] = { 0 };
// 存储客户端的地址信息结构体
struct sockaddr_in cin_temp;
socklen_t addrlen = sizeof(cin_temp);
while (1) {
// 读取数据
bzero(buf, sizeof(buf));
if (recvfrom(sfd, buf, sizeof(buf), 0, (struct sockaddr*)&cin_temp, &addrlen) < 0) {
ERR_MSG("recvfrom error");
return -1;
}
printf("from client-[%s : %d] buf = %s\n", inet_ntoa(cin_temp.sin_addr), ntohs(cin_temp.sin_port), buf);
// 发送数据
bzero(buf, sizeof(buf));
printf("input >");
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf) - 1] = '\0';
if (sendto(sfd, buf, strlen(buf), 0, (struct sockaddr*)&cin_temp, addrlen) < 0) {
ERR_MSG("sendto error");
return -1;
}
}
return 0;
}
客户端
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#define ERR_MSG(msg) \
do { \
fprintf(stderr, "line : %d\n", __LINE__); \
perror(msg); \
} while (0)
#define SER_IP "192.168.0.122"
#define SER_PORT 8888
#define CLI_IP "192.168.0.122"
#define CLI_PORT 6666
int main(int argc, char const* argv[])
{
// 创建报式套接字
int cfd = socket(AF_INET, SOCK_DGRAM, 0);
if (cfd < 0) {
ERR_MSG("socket error");
return -1;
}
printf("socket successful __%d__\n", __LINE__);
// 绑定客户端IP地址和端口(非必须)
// 填充地址信息结构体(绑定使用)
struct sockaddr_in cin;
cin.sin_family = AF_INET;
cin.sin_port = htons(CLI_PORT);
cin.sin_addr.s_addr = inet_addr(CLI_IP);
if (bind(cfd, (struct sockaddr*)&cin, sizeof(cin)) < 0) {
ERR_MSG("bind error");
return -1;
}
printf("bind successful __%d__\n", __LINE__);
// 填充信息结构体(sendto使用)
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(SER_PORT);
sin.sin_addr.s_addr = inet_addr(SER_IP);
socklen_t addrlen = sizeof(sin);
char buf[128] = { 0 };
while (1) {
// 发送数据
printf("input >");
bzero(buf, sizeof(buf));
fgets(buf, sizeof(buf), stdin);
if (sendto(cfd, buf, strlen(buf), 0, (struct sockaddr*)&sin, addrlen) < 0) {
ERR_MSG("sendto error");
return -1;
}
// 接收数据
bzero(buf, sizeof(buf));
if (recvfrom(cfd, buf, sizeof(buf), 0, (struct sockaddr*)&sin, &addrlen) < 0) {
ERR_MSG("recvfrom error");
return -1;
}
printf("from server-[%s : %d] buf : %s\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), buf);
}
return 0;
}