net/AllocatedSocketAddress: add method SetPort()

This commit is contained in:
Max Kellermann 2017-05-17 09:27:18 +02:00
parent 77c747a8fd
commit e6e9b2041e
2 changed files with 66 additions and 2 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2012-2015 Max Kellermann <max.kellermann@gmail.com>
* Copyright (C) 2012-2017 Max Kellermann <max.kellermann@gmail.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@ -36,6 +36,14 @@
#include <sys/un.h>
#endif
#ifdef HAVE_TCP
#ifdef WIN32
#include <ws2tcpip.h>
#else
#include <netinet/in.h>
#endif
#endif
AllocatedSocketAddress &
AllocatedSocketAddress::operator=(SocketAddress src)
{
@ -82,3 +90,32 @@ AllocatedSocketAddress::SetLocal(const char *path) noexcept
}
#endif
#ifdef HAVE_TCP
bool
AllocatedSocketAddress::SetPort(unsigned port) noexcept
{
if (IsNull())
return false;
switch (GetFamily()) {
case AF_INET:
{
auto *a = (struct sockaddr_in *)(void *)address;
a->sin_port = htons(port);
return true;
}
case AF_INET6:
{
auto *a = (struct sockaddr_in6 *)(void *)address;
a->sin6_port = htons(port);
return true;
}
}
return false;
}
#endif

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2012-2015 Max Kellermann <max.kellermann@gmail.com>
* Copyright (C) 2012-2017 Max Kellermann <max.kellermann@gmail.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@ -143,6 +143,33 @@ public:
void SetLocal(const char *path) noexcept;
#endif
#ifdef HAVE_TCP
/**
* Extract the port number. Returns 0 if not applicable.
*/
gcc_pure
unsigned GetPort() const noexcept {
return ((SocketAddress)*this).GetPort();
}
/**
* @return true on success, false if this address cannot have
* a port number
*/
bool SetPort(unsigned port) noexcept;
static AllocatedSocketAddress WithPort(SocketAddress src,
unsigned port) noexcept {
AllocatedSocketAddress result(src);
result.SetPort(port);
return result;
}
AllocatedSocketAddress WithPort(unsigned port) const noexcept {
return WithPort(*this, port);
}
#endif
private:
void SetSize(size_type new_size) noexcept;
};