/* * Portable network messaging routines. * $Id$ * Copyright (c) 1997 by Tycho Softworks. * For conditions of distribution and reuse see product license. */ #include #include static ushort sequence = 0; SOCKET create_msgport(char *mask, int port, int backlog) { if(backlog) return tcpsocket(mask, port, backlog); else return udpsocket(mask, port); } size_t send_msgport(SOCKET so, SOCKMSG *buf, size_t len, bool flag) { size_t stat; memset(buf, 0, sizeof(SOCKMSG)); if(flag) ++sequence; buf->header.len = htonl(len); buf->sequence = sequence; stat = send(so, buf, len + sizeof(SOCKMSG), 0); if (stat > 0) return stat - sizeof(SOCKMSG); return stat; } size_t recv_msgport(SOCKET so, SOCKMSG *buf, size_t len, bool any) { int alen; size_t mlen; size_t stat; SOCKMSG saddr; for(;;) { alen = recv(so, &saddr, sizeof(saddr), MSG_PEEK); if(alen < 0) return stat; mlen = ntohl(saddr.header.len); if (mlen > len) mlen = len; stat = recvfrom(so, buf, mlen + sizeof(saddr), 0, (struct sockaddr *)&saddr, &alen); memcpy(buf, &saddr, alen); if (stat > 0) { if(any && buf->sequence != sequence) continue; return stat - sizeof(SOCKMSG); } return stat; } } size_t reply_msgport(SOCKET so, SOCKMSG *buf, SOCKMSG *org, size_t len) { size_t stat; SOCKMSG saddr; if(!org) org = buf; memcpy(&saddr, org, sizeof(saddr)); buf->header.len = htonl(len); stat = sendto(so, buf, len + sizeof(SOCKMSG), 0, (struct sockaddr *)&saddr, sizeof(saddr)); if (stat > 0) return stat - sizeof(SOCKMSG); return stat; }