summaryrefslogtreecommitdiffhomepage
path: root/NetEx/NetAddr.cpp
blob: 2e043f16ce092d8f726c433d142a4c78a6e846c9 (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
/*  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 "MemDebug.h"
#include "NetAddr.h"
#include "NetHost.h"
#include "NetLayer.h"
#include <ctype.h>

NetAddr::NetAddr(const char* host_name, WORD p)
    : addr(0), port(p)
{
    if (host_name && *host_name) {
        HOSTENT* h = 0;

        if (isdigit(*host_name)) {
            DWORD 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 = **(DWORD**) (h->h_addr_list);
            }
        }
    }

    Init();
}

NetAddr::NetAddr(DWORD a, WORD p)
    : addr(a), port(p)
{
    Init();
}

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

// +--------------------------------------------------------------------+

void
NetAddr::Init()
{
    ZeroMemory(&sadr, 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;
}

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

// +--------------------------------------------------------------------+

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

        if (size > sizeof(sadr))
            CopyMemory(&sadr, s, sizeof(sadr));
        else
            CopyMemory(&sadr, s, size);

        InitFromSockAddr();
    }
}