summaryrefslogtreecommitdiffhomepage
path: root/NetEx/NetAddr.cpp
blob: 5e5468d06b48f926436d1721508e869da970f84d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*  Starshatter: The Open Source Project
    Copyright (c) 2021-2022, Starshatter: The Open Source Project Contributors
    Copyright (c) 2011-2012, Starshatter OpenSource Distribution Contributors
    Copyright (c) 1997-2006, Destroyer Studios LLC.

    AUTHOR:       John DiCamillo


    OVERVIEW
    ========
    Network Address
*/

#include "NetAddr.h"

#ifdef _WIN32
#include <winsock2.h>
#else
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/socket.h>
#endif

#include <cctype>
#include <cstddef>
#include <cstdint>
#include <cstring>


NetAddr::NetAddr(const char* host_name, std::uint16_t p) :
    addr(0),
    port(p)
{
    if (host_name && *host_name) {
        struct hostent* h = nullptr;

        if (std::isdigit(*host_name)) {
            auto a = inet_addr(host_name);
            h = gethostbyaddr((const char*) &a, 4, AF_INET);
        }
        else {
            h = gethostbyname(host_name);
        }

        if (h) {
            if (h->h_addr_list) {
                addr = **(std::uint32_t**) (h->h_addr_list);
            }
        }
    }

    Init();
}


NetAddr::NetAddr(std::uint32_t a, std::uint16_t p) : 
    addr(a),
    port(p)
{
    Init();
}


NetAddr::NetAddr(const NetAddr& n) :
    addr(n.addr),
    port(n.port)
{
    Init();
}


void
NetAddr::Init()
{
    std::memset(&sadr, 0, sizeof(sadr));

    sadr.sin_family      = AF_INET;
    sadr.sin_port        = ::htons(port);
    sadr.sin_addr.s_addr = addr;
}


void
NetAddr::InitFromSockAddr()
{
    addr = sadr.sin_addr.s_addr;
    port = ::ntohs(sadr.sin_port);
}


sockaddr*
NetAddr::GetSockAddr() const
{
    return (sockaddr*) &sadr;
}


std::size_t
NetAddr::GetSockAddrLength() const
{
    return sizeof(sadr);
}


void
NetAddr::SetSockAddr(sockaddr* s, int size)
{
    if (s) {
        std::memset(&sadr, 0, sizeof(sadr));

        if (size > sizeof(sadr))
            std::memcpy(&sadr, s, sizeof(sadr));
        else
            std::memcpy(&sadr, s, sizeof(sadr));

        InitFromSockAddr();
    }
}