|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdint.h> |
| 3 | +#include <sys/types.h> |
| 4 | +#include <sys/socket.h> |
| 5 | +#include <arpa/inet.h> |
| 6 | +#include <netinet/in.h> |
| 7 | +#include <net/if.h> |
| 8 | +#include <string.h> |
| 9 | +#include <sys/time.h> |
| 10 | +#include <sys/ioctl.h> |
| 11 | +#include <time.h> |
| 12 | +#include <stdarg.h> |
| 13 | +#include <unistd.h> |
| 14 | +#include <errno.h> |
| 15 | + |
| 16 | +int printc(char* ch,int rn, void *buf); |
| 17 | + |
| 18 | +int main(int argc,char *argv[]) |
| 19 | +{ |
| 20 | + int port ; |
| 21 | + printf("argc = %d\n",argc); |
| 22 | + printf("usage:%s port\n",basename(argv[0])); |
| 23 | + if(argc<2){ |
| 24 | + port = 514; |
| 25 | + }else{ |
| 26 | + port = atoi(argv[1]); |
| 27 | + } |
| 28 | + struct sockaddr_in addr; |
| 29 | + struct in_addr in_addr_1; |
| 30 | + int addr_len = sizeof(struct sockaddr_in); |
| 31 | + char buf[1500]; |
| 32 | + int len,addrlen,ret; |
| 33 | + int fd = socket(AF_INET, SOCK_DGRAM, 0); |
| 34 | + |
| 35 | + if(fd<0) |
| 36 | + printf("create socket failed\n"); |
| 37 | + int opt=1; |
| 38 | + int opt_len = sizeof(opt); |
| 39 | + setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(char*)&opt,opt_len); |
| 40 | + //setsockopt(fd,SOL_SOCKET,SO_REUSEPORT,(char*)&opt,opt_len); |
| 41 | + bzero(&addr,sizeof(addr)); |
| 42 | + addr.sin_family = AF_INET; |
| 43 | + addr.sin_port = htons(port); |
| 44 | + addr.sin_addr.s_addr= htonl(INADDR_ANY);//inet_addr("127.0.0.1"); |
| 45 | + if((ret=bind(fd,(struct sockaddr *)&addr,sizeof(addr))) < 0){ |
| 46 | + printf("bind failed.fd=%d,ret=%d,error=%d,%s\n",fd,ret,errno,strerror(errno)); |
| 47 | + return -1; |
| 48 | + }else{ |
| 49 | + printf("bind success\n"); |
| 50 | + } |
| 51 | + int cnt = 0; |
| 52 | + while(1){ |
| 53 | + cnt++; |
| 54 | + bzero(buf,sizeof(buf)); |
| 55 | + len = recvfrom(fd,buf,sizeof(buf)-1,0,(struct sockaddr *)&addr,&addrlen); |
| 56 | + printf("[%s:%5d] len %4d,cnt = %d\n",inet_ntoa(addr.sin_addr),addr.sin_port,len,cnt); |
| 57 | + printc("data",len,buf); |
| 58 | + } |
| 59 | + |
| 60 | + |
| 61 | + return 0; |
| 62 | +} |
| 63 | + |
| 64 | +int printc(char* ch,int rn, void *buf) |
| 65 | +{ |
| 66 | + int i; |
| 67 | + unsigned char *pbuf; |
| 68 | + pbuf = (unsigned char*)buf; |
| 69 | + //printf("%s length %d\n",ch, rn); |
| 70 | + printf("\n"); |
| 71 | + for (i = 0; i < rn; i++) { |
| 72 | + if ((i % 8) == 0 && i != 0) |
| 73 | + printf( " #%d \n",i); |
| 74 | + printf( "%02X ", (*pbuf&0xff)); |
| 75 | + pbuf++; |
| 76 | + } |
| 77 | + printf( "\n\n"); |
| 78 | + return 0; |
| 79 | +} |
0 commit comments