# Network

## IpAddress

class sfml.network.IpAddress

  Encapsulate an IPv4 network address.

  `IpAddress` is an utility class for manipulating network addresses.

  It provides a set of class methods and conversion attributes to easily build or transform an IP address from/to various representations.

  Usage example:

      ip0 = sf.IpAddress()                             # an invalid address
      ip1 = sf.IpAddress.NONE                          # an invalid address (same as ip0)
      ip2 = sf.IpAddress.from_string("127.0.0.1")      # the local host address
      ip3 = sf.IpAddress.BROADCAST                     # the broadcast address
      ip4 = sf.IpAddress.from_bytes(192, 168, 1, 56)   # a local address
      ip5 = sf.IpAddress.from_string("my_computer")    # a local address created from a network name
      ip6 = sf.IpAddress.from_string("89.54.1.169")    # a distant address
      ip7 = sf.IpAddress.from_string("www.google.com") # a distant address created from a network name
      ip8 = sf.IpAddress.get_local_address()           # my address on the local network
      ip9 = sf.IpAddress.get_public_address()          # my address on the internet

  Note that `IpAddress` currently doesn’t support IPv6 nor other types of network addresses.

  NONE

    Value representing an empty/invalid address.

  LOCAL_HOST

    The “localhost” address (for connecting a computer to itself locally)

  BROADCAST

    The “broadcast” address (for sending UDP messages to everyone on a local network)

  classmethod from_string(string)

    Construct the address from a string.

    Here address can be either a decimal address (ex: “192.168.1.56”) or a network name (ex: “localhost”).

    Parameters:

      string (str) – IP address or network name

    Return type:

      `sfml.network.IpAddress`

  classmethod from_integer(integer)

    Construct the address from an integer.

    This constructor uses the internal representation of the address directly. It should be used for optimization purposes, and only if you got that representation from `IpAddress.integer`.

    Parameters:

      integer (integer) – 4 bytes of the address packed into a 32-bits integer

    Return type:

      `sfml.network.IpAddress`

  classmethod from_bytes(b0, b1, b2, b3)

    Construct the address from 4 bytes.

    Calling IpAddress.from_bytes(a, b, c, d) is equivalent to calling IpAddress.from_string(“a.b.c.d”), but safer as it doesn’t have to parse a string to get the address components.

    Parameters:

      - b0 (integer) – First byte of the address

      - b1 (integer) – Second byte of the address

      - b2 (integer) – Third byte of the address

      - b3 (integer) – Fourth byte of the address

    Return type:

      sfml.network.IpAddress

  string

    Get a string representation of the address.

    The returned string is the decimal representation of the IP address (like “192.168.1.56”), even if it was constructed from a host name.

    Type:

      string

  integer

    Get an integer representation of the address.

    The returned number is the internal representation of the address, and should be used for optimization purposes only (like sending the address through a socket). The integer produced by this function can then be converted back to a `IpAddress` with the proper constructor.

    Type:

      integer

  classmethod get_local_address()

    Get the computer’s local address.

    The local address is the address of the computer from the LAN point of view, i.e. something like 192.168.1.56. It is meaningful only for communications over the local network. Unlike `get_public_address()`, this function is fast and may be used safely anywhere.

    Return type:

      `sfml.network.IpAddress`

  classmethod get_public_address([timeout])

    Get the computer’s public address.

    The public address is the address of the computer from the internet point of view, i.e. something like 89.54.1.169. It is necessary for communications over the world wide web. The only way to get a public address is to ask it to a distant website; as a consequence, this function depends on both your network connection and the server, and may be very slow. You should use it as few as possible. Because this function depends on the network connection and on a distant server, you may use a time limit if you don’t want your program to be possibly stuck waiting in case there is a problem; this limit is deactivated by default.

    Parameters:

      timeout (sfml.system.Time) – Maximum time to wait

    Return type:

      `sfml.network.IpAddress`

## SocketException

exception sfml.network.SocketException(Exception)

  Main exception defined for all socket exceptions. Most of socket’s method can potentially raise one of the three following exceptions and you’ll use this one to catch any of them in one except statement.

exception sfml.network.SocketDisconnected(SocketException)

  In blocking mode, the socket may raise this exception to warm you it has been disconnected.

exception sfml.network.SocketNotReady(SocketException)

  In non-blocking mode, the socket will raise this exception if the socket is not ready to send/receive data yet.

exception sfml.network.SocketError(SocketException)

  In ** blocking mode**, the socket may raise this exception to warm you an unexpected error happened.

## Socket

class sfml.network.Socket

  > Base class for all the socket types.

  > This class mainly defines internal stuff to be used by derived classes.

  > The only public features that it defines, and which is therefore common to all the socket classes, is the blocking state. All sockets can be set as blocking or non-blocking.

  > In blocking mode, socket functions will hang until the operation completes, which means that the entire program (well, in fact the current thread if you use multiple ones) will be stuck waiting for your socket operation to complete.

  > In non-blocking mode, all the socket functions will return immediately. If the socket is not ready to complete the requested operation, the function simply raises the exception `SocketNotReady`.

  > The default mode, which is blocking, is the one that is generally used, in combination with threads or selectors. The non-blocking mode is rather used in real-time applications that run an endless loop that can poll the socket often enough, and cannot afford blocking this loop.

  DONE

    The socket has sent / received the data.

  NOT_READY

    The socket is not ready to send / receive data yet.

  DISCONNECTED

    The TCP socket has been disconnected.

  ERROR

    An unexpected error happened.

  ANY_PORT

    Special value that tells the system to pick any available port.

  blocking

    > The socket’s blocking state; blocking or non-blocking.

    Type:

      bool

## TcpSocket

class sfml.network.TcpSocket(Socket)

  > Specialized socket using the TCP protocol.

  > TCP is a connected protocol, which means that a TCP socket can only communicate with the host it is connected to.

  > It can’t send or receive anything if it is not connected.

  > The TCP protocol is reliable but adds a slight overhead. It ensures that your data will always be received in order and without errors (no data corrupted, lost or duplicated).

  > When a socket is connected to a remote host, you can retrieve informations about this host with the `remote_address` and `remote_port` attributes. You can also get the local port to which the socket is bound (which is automatically chosen when the socket is connected), with the `local_port` attribute.

  > Sending and receiving data can use only the low-level functions. The low-level functions process a raw sequence of bytes, and cannot ensure that one call to `send()` will exactly match one call to `receive()` at the other end of the socket.

  > The high-level interface is not implemented yet.

  > The socket is automatically disconnected when it is destroyed, but if you want to explicitly close the connection while the socket instance is still alive, you can call disconnect.

  > Usage example:

  >     # --- the client ---
  >     # create a socket and connect it to 192.168.1.50 on port 55001
  >     socket = sf.TcpSocket()
  >     socket.connect(sf.IpAddress.from_string("192.168.1.50"), 55001)

  >     # send a message to the connected host
  >     message = "Hi, I am a client".encode('utf-8')
  >     socket.send(message)

  >     # receive an answer from the server
  >     answer = socket.receive(1024)
  >     print("The server said: {0}".format(answer.decode('utf-8')))

  >     # --- the server ---
  >     # create a listener to wait for incoming connections on port 55001
  >     listener = sf.TcpListener()
  >     listener.listen(55001)

  >     # wait for a connection
  >     socket = listener.accept(socket)
  >     print("New client connected: {0}".format(socket.remote_address))

  >     # receive a message from the client
  >     message = socket.receive(1024)
  >     print("The client said: {0}".format(message.decode('utf-8')))

  >     # send an answer
  >     socket.send("Welcome, client".encode('utf-8'))

  local_port

    The port to which the socket is bound locally.

    If the socket is not connected, its value is 0.

    Type:

      integer

  remote_address

    The address of the connected peer.

    It the socket is not connected, its value `IpAddress.NONE`.

    Type:

      `sfml.network.IpAddress`

  remote_port

    The port of the connected peer to which the socket is connected.

    If the socket is not connected, its value is 0.

    Type:

      integer

  connect(remote_address, remote_port[, timeout])

    Connect the socket to a remote peer.

    In blocking mode, this function may take a while, especially if the remote peer is not reachable. The last parameter allows you to stop trying to connect after a given timeout. If the socket was previously connected, it is first disconnected.

    Raise:

      `SocketDisconnected`, `SocketNotReady` or `SocketError`

    Parameters:

      - remote_address (sfml.network.IpAddress) – Address of the remote peer

      - remote_port (integer) – Port of the remote peer

      - timeout (sfml.system.Time) – Optional maximum time to wait

  disconnect()

    Disconnect the socket from its remote peer.

    This function gracefully closes the connection. If the socket is not connected, this function has no effect.

  send(data)

    Send raw data to the remote peer.

    This function will fail if the socket is not connected.

    Raise:

      `SocketDisconnected`, `SocketNotReady` or `SocketError`

    Parameters:

      data (bytes) – The sequence of bytes to send

  receive(size)

    Receive raw data from the remote peer.

    In blocking mode, this function will wait until some bytes are actually received. This function will fail if the socket is not connected.

    Note

    The received data’s length may be different from the asked length.

    Raise:

      `SocketDisconnected`, `SocketNotReady` or `SocketError`

    Parameters:

      size (integer) – Maximum number of bytes that can be received

    Returns:

      A sequence of bytes

    Return type:

      bytes

## UdpSocket

class sfml.network.UdpSocket(Socket)

  Specialized socket using the UDP protocol.

  A UDP socket is a connectionless socket.

  Instead of connecting once to a remote host, like TCP sockets, it can send to and receive from any host at any time.

  It is a datagram protocol: bounded blocks of data (datagrams) are transferred over the network rather than a continuous stream of data (TCP). Therefore, one call to send will always match one call to receive (if the datagram is not lost), with the same data that was sent.

  The UDP protocol is lightweight but unreliable. Unreliable means that datagrams may be duplicated, be lost or arrive reordered. However, if a datagram arrives, its data is guaranteed to be valid.

  UDP is generally used for real-time communication (audio or video streaming, real-time games, etc.) where speed is crucial and lost data doesn’t matter much.

  Sending and receiving data can only use the low-level functions. The low-level functions process a raw sequence of bytes. The high-level method is not implemented.

  It is important to note that `UdpSocket` is unable to send datagrams bigger than `MAX_DATAGRAM_SIZE`. In this case, it returns an error and doesn’t send anything.

  If the socket is bound to a port, it is automatically unbound from it when the socket is destroyed. However, you can unbind the socket explicitly with the `unbind()` function if necessary, to stop receiving messages or make the port available for other sockets.

  Usage example:

      # --- the client ---
      # create a socket and bind it to the port 55001
      socket = sf.UdpSocket()
      socket.bind(55001)

      # send a message to 192.168.1.50 on port 55002
      message = "Hi, I am {0}".format(sf.IpAddress.get_local_address().string)
      socket.send(message.encode('utf-8'), sf.IpAddress.from_string("192.168.1.50"), 55002)

      # receive an answer (most likely from 192.168.1.50, but could be anyone else)
      answer, sender, port = socket.receive(1024)
      print("{0} said: {1}".format(sender.string, answer.decode('utf-8')))

      # --- the server ---
      # create a socket and bind it to the port 55002
      socket = sf.UdpSocket()
      socket.bind(55002)

      # receive a message from anyone
      message, sender, port = socket.receive(1024)
      print("{0} said: {1}".format(ip.string, message.decode('utf-8')))

      # send an answer
      answer = "Welcome {0}".format(sender.string)
      socket.send(answer, sender, port)

  MAX_DATAGRAM_SIZE

    The maximum number of bytes that can be sent in a single UDP datagram.

  local_port

    The port to which the socket is bound locally.

    If the socket is not connected, its value is 0.

    Type:

      integer

  bind(port)

    Bind the socket to a specific port.

    Binding the socket to a port is necessary for being able to receive data on that port. You can use the special value `Socket.ANY_PORT` to tell the system to automatically pick an available port, and then get the chosen port via the attribute local_port.

    Raise:

      `SocketDisconnected`, `SocketNotReady` or `SocketError`

    Parameters:

      port (integer) – Port to bind the socket to

  unbind()

    Unbind the socket from the local port to which it is bound.

    The port that the socket was previously using is immediately available after this function is called. If the socket is not bound to a port, this function has no effect.

  send(data, remote_address, port)

    Send raw data to a remote peer.

    Make sure that size is not greater than `MAX_DATAGRAM_SIZE`, otherwise this function will fail and no data will be sent.

    Raise:

      `SocketDisconnected`, `SocketNotReady` or `SocketError`

    Parameters:

      - data (bytes) – The sequence of bytes to send

      - remote_address (sfml.network.IpAddress) – Address of the receiver

      - port (integer) – Port of the receiver to send the data to

  receive(size)

    Receive raw data from a remote peer.

    In blocking mode, this function will wait until some bytes are actually received. Be careful to use a buffer which is large enough for the data that you intend to receive, if it is too small then an error will be returned and all the data will be lost.

    Raise:

      `SocketDisconnected`, `SocketNotReady` or `SocketError`

    Parameters:

      size (integer) – Maximum number of bytes that can be received

    Returns:

      A tuple with the sequence of bytes received, the remote address and the port used.

    Return type:

      tuple (bytes, sfml.network.IpAddress, integer)

## TcpListener

class sfml.network.TcpListener(Socket)

  `Socket` that listens to new TCP connections.

  A listener socket is a special type of socket that listens to a given port and waits for connections on that port.

  This is all it can do.

  When a new connection is received, you must call accept and the listener returns a new instance of `TcpSocket` that is properly initialized and can be used to communicate with the new client.

  Listener sockets are specific to the TCP protocol, UDP sockets are connectionless and can therefore communicate directly. As a consequence, a listener socket will always return the new connections as `TcpSocket` instances.

  A listener is automatically closed on destruction, like all other types of socket. However if you want to stop listening before the socket is destroyed, you can call its `close()` function.

  Usage example:

      # create a listener socket and make it wait for new connections on port 55001
      listener = sf.TcpListener()
      listener.listen(55001)

      # endless loop that waits for new connections
      while running:
         try:
            client = listener.accept()

         except sf.SocketException as error:
            print("An error occurred! Error: {0}".format(error))
            exit(1)

         # a new client just connected!
         print("New connection received from {0}".format(client.remote_address))
         do_something_with(client)

  local_port

    The port to which the socket is bound locally.

    If the socket is not listening to a port, its value is 0.

    Type:

      integer

  listen(port)

    Start listening for connections.

    This functions makes the socket listen to the specified port, waiting for new connections. If the socket was previously listening to another port, it will be stopped first and bound to the new port.

    Raise:

      `SocketDisconnected`, `SocketNotReady` or `SocketError`

    Parameters:

      port (integer) – Port to listen for new connections

  close()

    Stop listening and close the socket.

    This function gracefully stops the listener. If the socket is not listening, this function has no effect.

  accept()

    Accept a new connection.

    If the socket is in blocking mode, this function will not return until a connection is actually received.

    Raise:

      `SocketDisconnected`, `SocketNotReady` or `SocketError`

    Returns:

      `Socket` that holds the new connection

    Return type:

      `sfml.network.TcpSocket`