UDP回射服务器
udpserv01.c
#include <stdio.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define SERV_PORT 5000
#define MAXLINE 1024
void dg_echo(int sockfd, struct sockaddr *pcliaddr, socklen_t clilen);
int main(int argc, char **argv)
{
int sockfd;
struct sockaddr_in servaddr, cliaddr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
dg_echo(sockfd, (struct sockaddr *) &cliaddr, sizeof(cliaddr));
return 0;
}
void dg_echo(int sockfd, struct sockaddr *pcliaddr, socklen_t clilen)
{
int n;
socklen_t len;
char msg[MAXLINE];
for ( ; ; ) {
len = clilen;
n = recvfrom(sockfd, msg, MAXLINE, 0, pcliaddr, &len);
sendto(sockfd, msg, n, 0, pcliaddr, len);
}
}
UDP回射客户端
udpcli01.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define SERV_PORT 5000
#define MAXLINE 1024
void dg_cli(FILE *fp, int sockfd, const struct sockaddr *pservaddr, socklen_t servlen);
int main(int argc, char **argv)
{
int sockfd;
struct sockaddr_in servaddr;
if (argc != 2){
printf("usage: udpcli <IPaddress>");
exit(0);
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
dg_cli(stdin, sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
exit(0);
}
void dg_cli(FILE *fp, int sockfd, const struct sockaddr *pservaddr, socklen_t servlen)
{
int n;
char sendline[MAXLINE];
char recvline[MAXLINE];
while (fgets(sendline, MAXLINE, fp) != NULL){
sendto(sockfd, sendline, strlen(sendline), 0, pservaddr, servlen);
n = recvfrom(sockfd, recvline, MAXLINE, 0, NULL, NULL);
recvline[n] = 0; // null terminate
fputs(recvline, stdout);
}
}