1 /* 2 * Copyright 2008, Oliver Tappe, zooey@hirschkaefer.de. 3 * Distributed under the terms of the MIT license. 4 */ 5 6 7 #include <NetAddress.h> 8 9 #include <errno.h> 10 #include <netinet/in.h> 11 #include <stdio.h> 12 #include <stdlib.h> 13 #include <string.h> 14 15 16 void 17 checkNetAddr(const BNetAddress& netAddr, uint32 nwAddr, uint16 nwPort) 18 { 19 int32 status; 20 in_addr addr; 21 unsigned short port; 22 if ((status = netAddr.GetAddr(addr, &port)) != B_OK) { 23 fprintf(stderr, 24 "failed to get in_addr/port from localhost address: %s\n", 25 strerror(status)); 26 exit(1); 27 } 28 if (addr.s_addr != nwAddr) { 29 fprintf(stderr, "expected in_addr %lx - got %x\n", nwAddr, addr.s_addr); 30 exit(1); 31 } 32 uint16 hostPort = ntohs(nwPort); 33 if (port != hostPort) { 34 fprintf(stderr, "expected port %u - got %u\n", hostPort, port); 35 exit(1); 36 } 37 38 sockaddr_in sockaddr; 39 if ((status = netAddr.GetAddr(sockaddr)) != B_OK) { 40 fprintf(stderr, 41 "failed to get sockaddr_in from netAddr: %s\n", 42 strerror(status)); 43 exit(1); 44 } 45 if (sockaddr.sin_family != AF_INET) { 46 fprintf(stderr, "expected sockaddr-family %u - got %u\n", AF_INET, 47 sockaddr.sin_family); 48 exit(1); 49 } 50 if (sockaddr.sin_port != nwPort) { 51 fprintf(stderr, "expected sockaddr-port %x - got %x\n", nwPort, 52 sockaddr.sin_port); 53 exit(1); 54 } 55 if (sockaddr.sin_addr.s_addr != nwAddr) { 56 fprintf(stderr, "expected sockaddr-address %lx - got %x\n", nwAddr, 57 sockaddr.sin_addr.s_addr); 58 exit(1); 59 } 60 } 61 62 63 int 64 main(int argc, const char* const* argv) 65 { 66 BNetAddress netAddr; 67 if (sizeof(netAddr) != 52) { 68 fprintf(stderr, "expected sizeof(netAddr) to be 52 - is %ld\n", 69 sizeof(netAddr)); 70 exit(1); 71 } 72 73 netAddr.SetTo("localhost", 123); 74 checkNetAddr(netAddr, htonl(0x7F000001), htons(123)); 75 76 netAddr.SetTo(htonl(0x7F000001), 123); 77 checkNetAddr(netAddr, htonl(0x7F000001), htons(123)); 78 79 in_addr addr; 80 addr.s_addr = htonl(0x7F000001); 81 netAddr.SetTo(addr, 54321); 82 checkNetAddr(netAddr, htonl(0x7F000001), htons(54321)); 83 84 sockaddr_in sockaddr; 85 sockaddr.sin_family = AF_INET; 86 sockaddr.sin_addr.s_addr = htonl(0x7F000001); 87 sockaddr.sin_port = htons(54321); 88 netAddr.SetTo(sockaddr); 89 checkNetAddr(netAddr, htonl(0x7F000001), htons(54321)); 90 91 printf("Everything went fine.\n"); 92 93 return 0; 94 } 95