UNIX环境高级编程学习之第十六章网络IPC:套接字 – 简单UDP Socket 通信
[code lang=”cpp”]/* User:Lixiujie
* Date:20101122
* Desc:简单Udp通信,向其它连接过来的发送uptime信息。
* File:udp_client1.c
* System:Ubuntu 64bit
* gcc udp_client1.c udp_client1
* udp_client1 0.0.0.0 7878
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

#include <unistd.h>

#include <sys/types.h>
#include <sys/socket.h> /* socket bind listen connect accept send recv sendto recvfrom */
#include <arpa/inet.h> /* htons ntohs htonl ntohl inet_addr inet_ntoa */
#include <netinet/in.h> /* sockaddr_in */

#define BUFLEN 128

/* create udp */
int initserver(int type, const struct sockaddr *addr, socklen_t alen, int qlen){
int fd;
int err = 0;
/* 创建 */
if ((fd = socket(addr->sa_family, type, 0)) < 0){
return -1;
}
/* 绑定 */
if (bind(fd, addr, alen) < 0){
err = errno;
goto errout;
}
/* 监听数 */
if (SOCK_STREAM == type || SOCK_SEQPACKET == type){
if (listen(fd, qlen) < 0) {
err = errno;
goto errout;
}
}
return fd;
errout:
close(fd);
errno = err;
return -1;
}

int main(int argc, char *argv[]){
if (argc != 3){
printf("arg err!/n");
return -1;
}
int myfd, ret;
FILE *fp;
char szBuf[BUFLEN];
struct sockaddr_in my_addr,you_addr;
socklen_t alen = sizeof(struct sockaddr);
/* 设置本身IP和端口 */
memset((void *)&my_addr, 0, alen);
my_addr.sin_family = AF_INET;
my_addr.sin_addr.s_addr = inet_addr(argv[1]);
my_addr.sin_port = htons(atoi(argv[2]));

if ((myfd = initserver(SOCK_DGRAM, (struct sockaddr *)&my_addr, alen, 0)) > 0){
while (1){
alen = sizeof(struct sockaddr);
memset((void *)&you_addr, 0 , alen);
memset(szBuf, 0, BUFLEN);
ret = recvfrom(myfd, szBuf, BUFLEN, 0, (struct sockaddr*)&you_addr, &alen);
if (ret < 0){
printf("recvfrom err=%s!/n", strerror(errno));
close(myfd);
return -1;
}
printf("udp recvfrom:ip=%s, port=%d, data:%s /n", inet_ntoa(you_addr.sin_addr), ntohs(you_addr.sin_port), szBuf);
if ((fp = popen("/usr/bin/uptime", "r")) == NULL){
memset(szBuf, 0, BUFLEN);
sprintf(szBuf, "error: %s/n", strerror(errno));
sendto(myfd, szBuf, strlen(szBuf), 0, (struct sockaddr*)&you_addr, alen);
}else{
memset(szBuf, 0, BUFLEN);
while (fgets(szBuf, BUFLEN, fp) != NULL){
sendto(myfd, szBuf, strlen(szBuf), 0, (struct sockaddr*)&you_addr, alen);
memset(szBuf, 0, BUFLEN);
}
pclose(fp);
}
}
}else{
printf("initserver err=%s!/n", strerror(errno));
close(myfd);
return -1;
}
close(myfd);
return 0;
}

[/code]

发表评论