// main.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8000
#define IP "192.168.126.140"
#define PRINT_ERR(msg) \
do \
{ \
perror(msg); \
return -1; \
} while (0)
int main(int argc, const char *argv[])
{
int sfd = socket(AF_INET, SOCK_DGRAM, 0);
if (-1 == sfd)
PRINT_ERR("socket");
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(IP);
sin.sin_port = htons(PORT);
if (bind(sfd, (struct sockaddr *)&sin, sizeof(sin)) < 0)
PRINT_ERR("bind");
else
printf("链接成功\n");
char buff[100];
struct sockaddr_in cin;
socklen_t cin_len = sizeof(cin);
int res;
while (1)
{
res = recvfrom(sfd, buff, sizeof(buff), 0, (struct sockaddr *)&cin, &cin_len);
if (res < 0)
PRINT_ERR("recvfrom");
buff[res] = '\0';
printf("%s", buff);
printf("input 》》");
fgets(buff, sizeof(buff), stdin);
res = sendto(sfd, buff, sizeof(buff), 0, (struct sockaddr *)&cin, cin_len);
if (0 > res)
PRINT_ERR("sendto");
}
close(sfd);
return 0;
}
// server.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8000
#define IP "192.168.126.140"
#define PRINT_ERR(msg) \
do \
{ \
perror(msg); \
return -1; \
} while (0)
int main(int argc, const char *argv[])
{
int sfd = socket(AF_INET, SOCK_DGRAM, 0);
if (-1 == sfd)
PRINT_ERR("socket");
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(IP);
sin.sin_port = htons(PORT);
// if(bind(sfd,(struct sockaddr *)&sin,sizeof(sin)) < 0)
// PRINT_ERR("bind");
// else printf("链接成功\n");
char buff[100];
struct sockaddr_in cin;
socklen_t cin_len = sizeof(cin);
int res;
while(1)
{
printf("input 》》");
fgets(buff,sizeof(buff),stdin);
res = sendto(sfd,buff,sizeof(buff),0,(struct sockaddr *)&sin,sizeof(sin));
if(0 > res)
PRINT_ERR("sendto");
res = recvfrom(sfd,buff,sizeof(buff),0,(struct sockaddr *)&cin,&cin_len);
if( res < 0)
PRINT_ERR("recvfrom");
buff[res] = '\0';
printf("%s",buff);
}
close(sfd);
return 0;
}