1. 利用现成的echo服务端与自己写的client端进行udp通信
2. 代码
-
cong@msi:/work/test/tcpip/14udp/client$ cat client.c
-
#include "utils.h"
-
-
//#define TIME_SERV_ADDR "192.168.4.98"
-
#define TIME_SERV_ADDR "127.0.0.1"
-
-
char * sock_ntop(const struct sockaddr *sa, socklen_t salen)
-
{
-
char portstr[8];
-
static char str[128]; /* Unix domain is largest */
-
struct sockaddr_in *sin = (struct sockaddr_in *) sa;
-
//只处理AF_INET 协议族
-
if (inet_ntop(AF_INET, &sin->sin_addr, str, sizeof(str)) == NULL)
-
return(NULL);
-
if (ntohs(sin->sin_port) != 0) {
-
snprintf(portstr, sizeof(portstr), ":%d", ntohs(sin->sin_port));
-
strcat(str, portstr);
-
}
-
return(str);
-
}
-
-
void dg_cli(FILE* fp, int sockfd, const struct sockaddr* pservaddr, socklen_t servlen)
-
{
-
int n;
-
char sendline[MAXLINE], recvline[MAXLINE];
-
socklen_t len;
-
struct sockaddr* preply_addr;
-
preply_addr = malloc(servlen);
-
while(fgets(sendline, MAXLINE, fp) != NULL)
-
{
-
//write(sockfd, sendline, strlen(sendline));
-
sendto(sockfd, sendline, strlen(sendline), 0, pservaddr, servlen);
-
-
len = servlen;
-
n = recvfrom(sockfd, recvline, MAXLINE, 0, preply_addr, &len);
-
if( (len!=servlen) || (memcmp(pservaddr, preply_addr, len)!= 0))
-
{
-
dbmsg("reply from %s (ignored)",sock_ntop(preply_addr,len));
-
continue;
-
}
-
recvline[n] = 0;
-
fputs(recvline, stdout);
-
}
-
}
-
-
int main ( int argc, char *argv[] )
-
{
-
int sockfd, n;
-
struct sockaddr_in servaddr;
-
char recvline[1024];
-
//sockfd = socket(AF_INET, SOCK_STREAM, 0);
-
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
-
if(sockfd < 0)
-
return -1;
-
bzero(&servaddr, sizeof(servaddr));
-
servaddr.sin_family = AF_INET;
-
servaddr.sin_port = htons(7);
-
inet_pton(AF_INET, TIME_SERV_ADDR, &servaddr.sin_addr);
-
-
//connect(sockfd, (const struct sockaddr*)&servaddr, sizeof(servaddr));
-
dbmsg("next dg_cli");
-
dg_cli(stdin, sockfd, (const struct sockaddr*)&servaddr, sizeof(servaddr));
-
return EXIT_SUCCESS;
-
}
3.错误分析
client端没有收到回复的原因是本机的echo服务没有打开
本机配置一下:
-
cong@msi:/tmp$ sudo apt-get install xinetd
-
cong@msi:/tmp$ sudo vi /etc/inetd.conf
-
echo dgram udp wait root internal -->配置echo服务是udp
-
#echo stream tcp nowait root internal -->配置echo服务是tcp
-
cong@msi:/tmp$ sudo /etc/init.d/xinetd restart
-
cong@msi:/tmp$ netstat -nlp -->查看端口
-
tcp 0 0 0.0.0.0:7 0.0.0.0:* LISTEN - -->配置echo服务是tcp就会出现这一行
-
udp 0 0 0.0.0.0:7 0.0.0.0:* - -->配置echo服务是udp,就会出现这一行
netstat -nlp查看时出现
udp 0 0 0
.0
.0
.0
:7 0
.0
.0
.0
:* - -->出现这一行就是我们需要的
client.rar (下载后改名为client.tar.gz)
阅读(1428) | 评论(0) | 转发(0) |