Class: UDPSocket

Inherits:
IPSocket show all
Defined in:
lib/rubysl/socket/socket.rb

Constant Summary collapse

FFI =
Rubinius::FFI

Instance Method Summary collapse

Methods inherited from IPSocket

#addr, getaddress, #peeraddr, #recvfrom, #recvfrom_nonblock

Methods inherited from BasicSocket

#close_read, #close_write, do_not_reverse_lookup, do_not_reverse_lookup=, for_fd, from_descriptor, #from_descriptor, #getpeername, #getsockname, #getsockopt, #recv, #recv_nonblock, #recvfrom, #setsockopt, #shutdown

Constructor Details

#initialize(socktype = Socket::AF_INET) ⇒ UDPSocket

Returns a new instance of UDPSocket.



970
971
972
973
974
975
976
977
978
# File 'lib/rubysl/socket/socket.rb', line 970

def initialize(socktype = Socket::AF_INET)
  @socktype = socktype
  status = Socket::Foreign.socket @socktype,
                                  Socket::SOCK_DGRAM,
                                  Socket::IPPROTO_UDP
  Errno.handle 'socket(2)' if status < 0

  IO.setup self, status, nil, true
end

Instance Method Details

#bind(host, port) ⇒ Object



980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
# File 'lib/rubysl/socket/socket.rb', line 980

def bind(host, port)
  @host = host.to_s if host
  @port = port.to_s if port

  addrinfos = Socket::Foreign.getaddrinfo(@host,
                                         @port,
                                         @socktype,
                                         Socket::SOCK_DGRAM, 0,
                                         Socket::AI_PASSIVE)

  status = -1

  addrinfos.each do |addrinfo|
    flags, family, socket_type, protocol, sockaddr, canonname = addrinfo

    status = Socket::Foreign.bind descriptor, sockaddr

    break if status >= 0
  end

  if status < 0
    Errno.handle 'bind(2)'
  end

  status
end

#connect(host, port) ⇒ Object



1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
# File 'lib/rubysl/socket/socket.rb', line 1007

def connect(host, port)
  sockaddr = Socket::Foreign.pack_sockaddr_in host, port, @socktype, Socket::SOCK_DGRAM, 0

  syscall = 'connect(2)'
  status = Socket::Foreign.connect descriptor, sockaddr

  if status < 0
    Errno.handle syscall
  end

  0
end

#inspectObject



1035
1036
1037
# File 'lib/rubysl/socket/socket.rb', line 1035

def inspect
  "#<#{self.class}:0x#{object_id.to_s(16)} #{@host}:#{@port}>"
end

#send(message, flags, *to) ⇒ Object



1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
# File 'lib/rubysl/socket/socket.rb', line 1020

def send(message, flags, *to)
  connect *to unless to.empty?

  bytes = message.length
  bytes_sent = 0

  FFI::MemoryPointer.new :char, bytes + 1 do |buffer|
    buffer.write_string message
    bytes_sent = Socket::Foreign.send(descriptor, buffer, bytes, flags)
    Errno.handle 'send(2)' if bytes_sent < 0
  end

  bytes_sent
end