0001 /** 0002 * Copyright IBM Corporation 2016 0003 * 0004 * Licensed under the Apache License, Version 2.0 (the "License"); 0005 * you may not use this file except in compliance with the License. 0006 * You may obtain a copy of the License at 0007 * 0008 * http://www.apache.org/licenses/LICENSE-2.0 0009 * 0010 * Unless required by applicable law or agreed to in writing, software 0011 * distributed under the License is distributed on an "AS IS" BASIS, 0012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 0013 * See the License for the specific language governing permissions and 0014 * limitations under the License. 0015 **/ 0016 0017 #if os(Linux) 0018 import Glibc 0019 #else 0020 import Darwin 0021 #endif 0022 0023 /** 0024 * Creates and a binds a socket to the specified port number and ip address. 0025 * The socket is then returned. 0026 */ 0027 public func createSocket(address: Address) -> Int32 0028 { 0029 var name = sockaddr_in() 0030 0031 // Create the socket 0032 let sockfd = socket(PF_INET, 1, 0) 0033 if sockfd < 0 { 0034 perror ("socket") 0035 //exit(EXIT_FAILURE) 0036 exit(1) // swift compiler issue 0037 } 0038 0039 // Make the address reusable for multiple runs 0040 var on: Int32 = 1 0041 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, socklen_t(sizeof(Int32))) 0042 0043 // Give the socket a name 0044 name.sin_family = sa_family_t(AF_INET) 0045 name.sin_port = UInt16(address.port).bigEndian 0046 var addr: UInt32 = 1 0047 inet_pton(AF_INET, address.ip, &addr) 0048 name.sin_addr.s_addr = addr 0049 // INADDR_ANY which equals 0 0050 // name.sin_addr.s_addr = in_addr_t(0) 0051 0052 var bindAddr = sockaddr() 0053 memcpy(&bindAddr, &name, Int(sizeof(sockaddr_in))) 0054 let addrSize: socklen_t = socklen_t(sizeof(sockaddr_in)) 0055 0056 // Bind name to socket 0057 if bind(sockfd, &bindAddr, addrSize) < 0 { 0058 perror("bind") 0059 //exit(EXIT_FAILURE) 0060 exit(1) // swift compiler issue 0061 } 0062 return sockfd 0063 } 0064