From 85fe75d1cbaf372f0a98558adcd5a612a0e19602 Mon Sep 17 00:00:00 2001 From: ShadowNinja Date: Wed, 5 Feb 2014 21:24:46 +0100 Subject: Add the option to bind to a specific address --- src/socket.cpp | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) (limited to 'src/socket.cpp') diff --git a/src/socket.cpp b/src/socket.cpp index 78ff364e5..00856fb00 100644 --- a/src/socket.cpp +++ b/src/socket.cpp @@ -92,24 +92,27 @@ void sockets_cleanup() Address::Address() { m_addr_family = 0; - memset(&m_address, 0, sizeof m_address); + memset(&m_address, 0, sizeof(m_address)); m_port = 0; } Address::Address(u32 address, u16 port) { + memset(&m_address, 0, sizeof(m_address)); setAddress(address); setPort(port); } Address::Address(u8 a, u8 b, u8 c, u8 d, u16 port) { + memset(&m_address, 0, sizeof(m_address)); setAddress(a, b, c, d); setPort(port); } Address::Address(const IPv6AddressBytes * ipv6_bytes, u16 port) { + memset(&m_address, 0, sizeof(m_address)); setAddress(ipv6_bytes); setPort(port); } @@ -334,12 +337,20 @@ UDPSocket::~UDPSocket() #endif } -void UDPSocket::Bind(u16 port) +void UDPSocket::Bind(Address addr) { if(socket_enable_debug_output) { dstream << "UDPSocket(" << (int) m_handle << ")::Bind(): " - << "port=" << port << std::endl; + << addr.serializeString() << ":" + << addr.getPort() << std::endl; + } + + if (addr.getFamily() != m_addr_family) + { + char errmsg[] = "Socket and bind address families do not match"; + errorstream << "Bind failed: " << errmsg << std::endl; + throw SocketException(errmsg); } if(m_addr_family == AF_INET6) @@ -347,12 +358,12 @@ void UDPSocket::Bind(u16 port) struct sockaddr_in6 address; memset(&address, 0, sizeof(address)); + address = addr.getAddress6(); address.sin6_family = AF_INET6; - address.sin6_addr = in6addr_any; - address.sin6_port = htons(port); + address.sin6_port = htons(addr.getPort()); if(bind(m_handle, (const struct sockaddr *) &address, - sizeof(struct sockaddr_in6)) < 0) + sizeof(struct sockaddr_in6)) < 0) { dstream << (int) m_handle << ": Bind failed: " << strerror(errno) << std::endl; @@ -364,9 +375,9 @@ void UDPSocket::Bind(u16 port) struct sockaddr_in address; memset(&address, 0, sizeof(address)); + address = addr.getAddress(); address.sin_family = AF_INET; - address.sin_addr.s_addr = INADDR_ANY; - address.sin_port = htons(port); + address.sin_port = htons(addr.getPort()); if(bind(m_handle, (const struct sockaddr *) &address, sizeof(struct sockaddr_in)) < 0) -- cgit v1.2.3