You are not logged in.

#1 2008-06-28 04:54:15

peets
Member
From: Montreal
Registered: 2007-01-11
Posts: 936
Website

how should I compare internet socket addresses?

I'm having my first go at rudimentary network programming. I need to compare two network addresses. What seems to me to be a general way of doing this is

struct sockaddr a, b;
a.sa_family == b.sa_family && a.sa_data == b.sa_data;

1. Is this The Right Way?
2. Is there some standard method that abbreviates this? Something like

struct sockaddr a, b;
sa_cmp(a, b);

While I'm at it, is there some standard ready-made method that, given an adress family (e.g. AF_INET) will return the only matching protocol family (e.g. PF_INET)? Is it absolutely safe to use them interchangeably? mpd does this

    switch (addrp->sa_family) {
#ifdef HAVE_TCP
    case AF_INET:
        pf = PF_INET;
        break;
#ifdef HAVE_IPV6
    case AF_INET6:
        pf = PF_INET6;
        break;
#endif
#endif /* HAVE_TCP */
#ifdef HAVE_UN
    case AF_UNIX:
        pf = PF_UNIX;
        break;
#endif /* HAVE_UN */
    default:
        FATAL("unknown address family: %i\n", addrp->sa_family);
    }

should I do it too?

Last edited by peets (2008-06-28 05:10:32)

Offline

#2 2008-06-28 07:32:06

sniffles
Member
Registered: 2008-01-23
Posts: 275

Re: how should I compare internet socket addresses?

sa_family_t sa_family        Address family.
char sa_data[]        Socket address (variable-length data).

(at least) On this machine :

/usr/include/bits/sockaddr.h:
typedef unsigned short int sa_family_t;

--

While I'm at it, is there some standard ready-made method that, given an adress family (e.g. AF_INET) will return the only matching protocol family (e.g. PF_INET)? Is it absolutely safe to use them interchangeably?

I don't know if it is absolutely safe [i.e. portable]. I believe on Linux AF_* = (corresponding) PF_*. i.e.: #define AF_INET PF_INET etc. (/usr/include/bits/socket.h)

--

should I do it too?

Well, you've said this is rudimentary stuff you're trying to do. Are you using IPV6 ? If not, perhaps stick to ipv4 and use sockaddr_in ? Also, write for the operating system(s) You use for now rather than try to be portable as far as C net programming goes.

Last edited by sniffles (2008-06-28 07:33:22)

Offline

#3 2008-06-28 16:45:34

peets
Member
From: Montreal
Registered: 2007-01-11
Posts: 936
Website

Re: how should I compare internet socket addresses?

Thanks for the info.

I'm writing a patch for mpd, so it should be as portable as the rest of mpd. I'll wrap the above AF => PF in a function and use it in two places.

Offline

Board footer

Powered by FluxBB