/** *This program is used for testing the network ip. */ #include <sys/types.h> /* See NOTES */ #include <stdio.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <errno.h> #include <time.h> #include <asm/ioctls.h> #include <signal.h> #include <linux/if.h> #include <linux/sockios.h>
#define MAX_LISTENERS 30 #define DBG_SERVER #ifdef DBG_SERVER #define DBG(x) x #else #define DBG(x) #endif
int get_src_bindip(int _iSocket) { struct ifreq if_req; int iIP = -1; int iRet = -1; struct sockaddr_in sin_a;
memset(&if_req, 0, sizeof(struct ifreq)); strncpy(if_req.ifr_name, "eth0", 6); if_req.ifr_name[4] = 0; if(_iSocket > 0) { iRet = ioctl(_iSocket, SIOCGIFADDR, &if_req); if(iRet < 0) { printf("Error %d %s\n", errno, strerror(errno)); return iRet; } } memcpy(&sin_a, &if_req.ifr_addr, sizeof(sin_a)); printf("ip is %s \n", inet_ntoa(sin_a.sin_addr)); return 0; }
int get_dst_ip(int _iSocket) { struct ifreq if_req; int iIP = -1; int iRet = -1; struct sockaddr_in sin_a; memset(&if_req, 0, sizeof(struct ifreq)); strncpy(if_req.ifr_name, "eth0", 6); if(_iSocket > 0) { iRet = ioctl(_iSocket, SIOCGIFDSTADDR, &if_req); if(iRet < 0) { printf("Error %d %s\n", errno, strerror(errno)); return iRet; } } memcpy(&sin_a, &if_req.ifr_addr, sizeof(sin_a)); printf("ip is %s \n", inet_ntoa(sin_a.sin_addr)); return 0; }
int main(int argc, char * argv[]) { struct sockaddr_in sin1; int size; struct timeval nTimeout; int iServerFD = -1; int iConnectFD = -1; int iSrcAddr = -1; int iDstAddr = -1; char cAddr[16] = {0}; char cMask[16] = {0}; iServerFD = socket(AF_INET, SOCK_STREAM, 0); if(iServerFD < 0) { DBG(printf("Create socket error!\n")); return iServerFD; } sin1.sin_family = AF_INET; sin1.sin_port = htons(8000); sin1.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(iServerFD, (struct sockaddr *)&sin1, sizeof(struct sockaddr_in)) < 0) { DBG(printf("Bind error!\n")); return -1; }
if( listen(iServerFD, MAX_LISTENERS) < 0) { DBG(printf("Listen failed!\n")); return -1; } printf("Start to listen....\n");
if((iConnectFD = accept(iServerFD, (struct sockaddr *)&sin1, &size)) < 0) { DBG(printf("Accept failed!\n")); return -1; } DBG(printf("got the client connected %s!\n", inet_ntoa(sin1.sin_addr))); getpeername(iConnectFD, (struct sockaddr *)&sin1, &size); DBG(printf("got the client connected %s!\n", inet_ntoa(sin1.sin_addr))); getsockname(iConnectFD, (struct sockaddr *)&sin1, &size); DBG(printf("The IP %s!\n", inet_ntoa(sin1.sin_addr)));
iSrcAddr = get_src_bindip(iConnectFD); iDstAddr = get_dst_ip(iConnectFD);
printf("The src is 0x%x dst is 0x%x\n", iSrcAddr, iDstAddr);
close(iServerFD); close(iConnectFD); return 0; }
|