udp_client

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <cutils/log.h>

#define BUFF_LEN 1024

void udp_msg_sender(int fd, struct sockaddr* dst, char* client_tx)
{
socklen_t len;
struct sockaddr_in src;

while(1){
char buf[BUFF_LEN] = {0};
strcpy(buf, client_tx);
len = sizeof(*dst);
ALOGD("UDP-C:TX:%s\n", buf);
sendto(fd, buf, strlen(buf), 0, dst, len);

memset(buf, 0, BUFF_LEN);
recvfrom(fd, buf, BUFF_LEN, 0, (struct sockaddr*)&src, &len);
ALOGD("UDP-C:RX:%s,port=%d,ip=%s\n", buf, ntohs(src.sin_port), inet_ntoa(src.sin_addr) );
sleep(1);
}
}

/*
client: socket-->sendto-->revcfrom-->close
usage: udp_client 9000 192.168.43.1 iamclient1
udp_client 9000 192.168.43.1 iamclient2
udp_client 9000 192.168.43.1 iamclient3
udp_client 9000 192.168.43.1 iamclient4
*/

int main(int argc, char* argv[])
{
int c;
int client_fd;
struct sockaddr_in server_addr;
int server_port = 0;
char* server_ip;
char* client_tx;

for(int i=0; i<argc; i++){
ALOGD("UDP-C:argv[%d]=%s\n", i, argv[i]);
}

server_port = atoi(argv[1]);
server_ip = argv[2];
client_tx = argv[3];

client_fd = socket(AF_INET, SOCK_DGRAM, 0);
if(client_fd < 0){
ALOGD("UDP-C:create socket fail!\n");
return -1;
}

memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(server_ip);
server_addr.sin_port = htons(server_port);

udp_msg_sender(client_fd, (struct sockaddr*)&server_addr, client_tx);
close(client_fd);
return 0;
}

posted on 2019-07-24 09:25  huangguanyuan  阅读(213)  评论(0编辑  收藏  举报

导航