title: Socket Server Example with Swift
body: <p>I tried to make an example of simple socket server.</p>
  
  <p>Build and run successfully.  However it doesn't work well.</p>
  
  <p>Client couldn't connect to this server.</p>
  
  <p>How to solve this problem?  I need your help, thanks.</p>
  
  <pre><code>import Foundation
  
  let BUFF_SIZE = 1024
  
  func initStruct&lt;S&gt;() -&gt; S {
      let struct_pointer = UnsafePointer&lt;S&gt;.alloc(1)
      let struct_memory = struct_pointer.memory
      struct_pointer.destroy()
      return struct_memory
  }
  
  func sockaddr_cast(p: ConstUnsafePointer&lt;sockaddr_in&gt;) -&gt; UnsafePointer&lt;sockaddr&gt; {
      return UnsafePointer&lt;sockaddr&gt;(p)
  }
  
  func socklen_t_cast(p: UnsafePointer&lt;Int&gt;) -&gt; UnsafePointer&lt;socklen_t&gt; {
      return UnsafePointer&lt;socklen_t&gt;(p)
  }
  
  var server_socket: Int32
  var client_socket: Int32
  var server_addr_size: Int
  var client_addr_size: Int
  
  var server_addr: sockaddr_in = initStruct()
  var client_addr: sockaddr_in = initStruct()
  
  var buff_rcv: Array&lt;CChar&gt; = []
  var buff_snd: String
  
  server_socket = socket(PF_INET, SOCK_STREAM, 0);
  
  if server_socket == -1
  {
      println("[Fail] Create Server Socket")
      exit(1)
  }
  else
  {
      println("[Success] Created Server Socket")
  }
  
  server_addr_size = sizeof(server_addr.dynamicType)
  memset(&amp;server_addr, 0, UInt(server_addr_size));
  
  server_addr.sin_family = sa_family_t(AF_INET)
  server_addr.sin_port = 4000
  server_addr.sin_addr.s_addr = UInt32(0x00000000)    // INADDR_ANY = (u_int32_t)0x00000000 ----- &lt;netinet/in.h&gt;
  
  let bind_server = bind(server_socket, sockaddr_cast(&amp;server_addr), socklen_t(server_addr_size))
  
  if bind_server == -1
  {
      println("[Fail] Bind Port");
      exit(1);
  }
  else
  {
      println("[Success] Binded Port");
  }
  
  if listen(server_socket, 5) == -1
  {
      println("[Fail] Listen");
      exit(1);
  }
  else
  {
      println("[Success] Listening : \(server_addr.sin_port) Port ...");
  }
  
  var n = 0
  
  while n &lt; 1
  {
      client_addr_size = sizeof(client_addr.dynamicType)
      client_socket = accept(server_socket, sockaddr_cast(&amp;client_addr), socklen_t_cast(&amp;client_addr_size))
  
      if client_socket == -1
      {
          println("[Fail] Accept Client Connection");
          exit(1);
      }
      else
      {
          println("[Success] Accepted Client : \(inet_ntoa(client_addr.sin_addr)) : \(client_addr.sin_port)");
      }
  
      read(client_socket, &amp;buff_rcv, UInt(BUFF_SIZE))
  
      println("[Success] Received : \(buff_rcv)")
  
      buff_snd = "\(strlen(buff_rcv)) : \(buff_rcv)"
  
      write(client_socket, &amp;buff_snd, strlen(buff_snd) + 1)
  
      close(client_socket)
  }
  </code></pre>