【UDP】C简单实现UDP IPv4 Client (V1_1.0)

为了配合测试一些功能,实现了一个简单的只有纯周期发送功能的udp client。

#include  
#include   
#include   
#include 
#include  
#include 
#include  
#include 
#include 

time_t rawtime;
struct tm* timeinfo;
char timeBuf[25] = {0}; //Sat Jan 13 17:36:34 2018

void getCurTime();

//使用方法#./a.out 1.1.1.1 12345
int main(int argc, char *argv[])
{
    if (argc != 3)
	{
		getCurTime();
		printf("%s usage:./%s svrIP svrPort\r\n", timeBuf, argv[0]);
		return 0;
	}
	
    struct sockaddr_in server_addr;  
    memset(&server_addr, 0, sizeof(server_addr)); 
    server_addr.sin_family = AF_INET;
	inet_pton(AF_INET, argv[1], &server_addr.sin_addr);
	server_addr.sin_port = htons(atoi(argv[2]));

	int sock = socket(AF_INET, SOCK_DGRAM, 0);  
    if (sock < 0)
	{  
		getCurTime();
        fprintf(stderr, "%s Failed to create socket.\r\n", timeBuf);
        exit(1);
    }
	
    while (1)
	{
		char buf[] =  "0123456";
        int ret = sendto(sock, buf, strlen(buf), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
        if (ret < 0)
		{
            getCurTime();
			fprintf(stderr, "%s Failed to sendto.\r\n", timeBuf);
            exit(1);
        }
		else
		{
			getCurTime();
			printf("%s Succeed to sendto.\r\n", timeBuf);
		}
        usleep(500 * 1000);//500ms
    }
	
    return 0; 
}

void getCurTime()
{
	time(&rawtime);
	timeinfo = localtime(&rawtime);
	memset(timeBuf, 0, sizeof(timeBuf));
	memcpy (timeBuf, asctime(timeinfo), 24);
}


#make udpClient

#./udpClient 1.1.1.1 12345

(end)

你可能感兴趣的:(Linux)