socintf.c (2755B)
1 /* 2 * 3 * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. 4 * 5 * Copyright 2007-2019 Broadcom Inc. All rights reserved. 6 * 7 * Requires: 8 * Socket library 9 * 10 * 11 * Provides: 12 * setup_socket 13 * wait_for_cnxn 14 */ 15 16 #include <unistd.h> 17 #include <stdlib.h> 18 #include <stdio.h> 19 20 #include <netinet/in.h> 21 #include <arpa/inet.h> 22 #include <memory.h> 23 #include <netdb.h> 24 25 #include <sys/types.h> 26 #include <sys/socket.h> 27 #include <sys/time.h> 28 29 int 30 setup_socket(int port) 31 { 32 struct sockaddr_in serv_addr; 33 int i; 34 int sockfd; 35 36 if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { 37 38 perror("server: can't open stream socket"); 39 exit(1); 40 } 41 42 /* 43 * Set socket option to reuse local address. This is supposed 44 * to have the effect of freeing up the local address. 45 */ 46 47 i = 1; 48 if (setsockopt(sockfd, SOL_SOCKET, 49 SO_REUSEADDR, (char *) &i, 4) < 0) { 50 perror("setsockopt"); 51 } 52 53 /* 54 * Set up server address... 55 */ 56 57 memset((void *) &serv_addr,0x0, sizeof(serv_addr)); 58 serv_addr.sin_family = AF_INET; 59 serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); 60 serv_addr.sin_port = htons(port); 61 62 /* 63 * Bind our local address & port 64 */ 65 66 if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { 67 perror("server: can't bind local address"); 68 exit(1); 69 } 70 71 /* 72 * Only process one connection at a time. 73 */ 74 75 listen(sockfd, 1); 76 77 return sockfd; 78 } 79 80 int 81 wait_for_cnxn(int sockfd) 82 { 83 struct sockaddr_in cli_addr; 84 socklen_t clilen; 85 int newsockfd; 86 87 clilen = sizeof(cli_addr); 88 newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); 89 90 if (newsockfd < 0) { 91 perror("accept"); 92 exit(1); 93 } 94 95 return newsockfd; 96 } 97 98 99 int 100 conn(char* server, int port) 101 { 102 struct sockaddr_in srv_addr; 103 int sockfd = -1; 104 struct hostent* hostentPtr = NULL; 105 106 /* 107 * Connect to host running Vera (ncsim) 108 */ 109 memset((void *)&srv_addr, 0, sizeof(srv_addr)); 110 hostentPtr = gethostbyname(server); 111 if(hostentPtr == NULL) { 112 printf("pli_client_attach: hostname lookup failed " 113 "for host [%s].\n", server); 114 perror("gethostbyname"); 115 goto error; 116 } 117 memcpy(&srv_addr.sin_addr,hostentPtr->h_addr,4); 118 119 srv_addr.sin_family = AF_INET; 120 srv_addr.sin_port = htons(port); 121 122 if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { 123 perror("server: can't open stream socket"); 124 goto error; 125 } 126 127 if (connect(sockfd, 128 (struct sockaddr*)&srv_addr, sizeof(srv_addr)) < 0) { 129 perror("connect"); 130 goto error; 131 } 132 return sockfd; 133 134 error: 135 close(sockfd); 136 return -1; 137 } 138 139 140 141 142