udp_server
#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 handle_udp_msg(int fd)
{
//Receive buffer,1024 bytes
char buf[BUFF_LEN]= {0};
socklen_t len;
int count;
//client_addr, save sender.
struct sockaddr_in client_addr;
while(1){
memset(buf, 0, BUFF_LEN);
len = sizeof(client_addr);
//recvfrom,may bloack
count = recvfrom(fd, buf, BUFF_LEN, 0, (struct sockaddr*)&client_addr, &len);
if(count == -1){
ALOGD("UDP-S:RX data fail!\n");
return;
}
ALOGD("UDP-S:RX:%s\n",buf);
ALOGD("UDP-S:TX:%s,port=%d,ip=%s\n", buf, ntohs(client_addr.sin_port), inet_ntoa(client_addr.sin_addr) );
//send to client.
sendto(fd, buf, BUFF_LEN, 0, (struct sockaddr*)&client_addr, len);
}
}
/*
server: socket-->bind-->recvfrom-->sendto-->close
usage: udp_server 9000 192.168.43.1
*/
int main(int argc, char* argv[])
{
int c;
int server_fd, ret;
int server_port = 0;
char* server_ip;
struct sockaddr_in server_addr;
for(int i=0; i<argc; i++){
ALOGD("UDP-S:argv[%d]=%s\n", i, argv[i]);
}
server_port = atoi(argv[1]);
server_ip = argv[2];
//AF_INET:IPV4;SOCK_DGRAM:UDP
server_fd = socket(AF_INET, SOCK_DGRAM, 0);
if(server_fd < 0){
ALOGD("UDP-S: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); /*IP,local address.*/
server_addr.sin_port = htons(server_port); /*PORT,local port.*/
ret = bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr));
if(ret < 0){
ALOGD("UDP-S:socket bind fail!\n");
return -1;
}
handle_udp_msg(server_fd);
close(server_fd);
return 0;
}
posted on 2019-07-24 09:25 huangguanyuan 阅读(807) 评论(0) 编辑 收藏 举报