#include
#include
#include
#include
#include
#include
#include
#include
#define SERV_PORT 25555 //服務(wù)器接聽端口號
#define BACKLOG 20 //請求隊(duì)列中允許請求數(shù)
#define BUF_SIZE 256 //緩沖區(qū)大小
int main(int argc, char *argv[])
{
int ret;
time_t tt;
struct tm *ttm;
char buf[BUF_SIZE];
int sockfd; //定義sock描述符
struct sockaddr_in serv_addr; //服務(wù)器IP地址和端口信息
if(argc != 2)
{
printf("命令行輸入有誤\n"); //命令行帶IP
return 1;
}
/**創(chuàng)建套接字**/
sockfd = socket(AF_INET, SOCK_DGRAM, 0); //TCP/IP協(xié)議,數(shù)據(jù)流套接字
if(sockfd == -1) //判斷socket函數(shù)的返回值
{
printf("調(diào)用socket函數(shù)創(chuàng)建鏈接失敗.\n");
return 0;
}
/**建立連接**/
bzero(&serv_addr, sizeof serv_addr);
serv_addr.sin_family = AF_INET; //TCP/IP協(xié)議
serv_addr.sin_port = htons(SERV_PORT); //設(shè)定端口號
//serv_addr.sin_addr.s_addr = INADDR_ANY; //使用回環(huán)地址 127.0.0.1
inet_aton(argv[1], (struct sockaddr *)&serv_addr.sin_addr.s_addr); //設(shè)定IP地址
while(1)
{
bzero(buf, sizeof buf); //首先清除緩沖區(qū)
tt = time(NULL);
ttm = localtime(&tt);
strcpy(buf, asctime(ttm)); //拷貝緩沖區(qū)數(shù)據(jù)
sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&serv_addr, sizeof serv_addr);
//接收數(shù)據(jù),然后放入緩沖區(qū)
sleep(2);
}
close(sockfd);
return 0;
}
分享標(biāo)題:[Linux網(wǎng)絡(luò)編程]UDP編程--UDP通信程序客戶端
標(biāo)題網(wǎng)址:
http://weahome.cn/article/pdjepc.html