Tcl UDP

Check-in [565c05d10a]
Login
Bounty program for improvements to Tcl and certain Tcl packages.
Tcl 2019 Conference, Houston/TX, US, Nov 4-8
Send your abstracts to [email protected]
or submit via the online form by Sep 9.

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Modifications to allow udp to compile under 8.7+
Timelines: family | ancestors | trunk
Files: files | file ages | folders
SHA3-256: 565c05d10a3857c144c3d9bc09a6fe477131cbea99ccad028a5532499da39a74
User & Date: seandeelywoods 2018-10-01 23:14:39
Context
2018-10-01
23:14
Modifications to allow udp to compile under 8.7+ Leaf check-in: 565c05d10a user: seandeelywoods tags: trunk
2017-12-26
14:27
Store HTML docs in repo since generation at install time mandates availability of mpexpand check-in: d9c46224c6 user: apnadkarni tags: trunk
Changes
Hide Diffs Unified Diffs Show Whitespace Changes Patch

Changes to generic/udp_tcl.c.

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
...
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
...
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
...
843
844
845
846
847
848
849








850
851
852
853
854
855
856
...
858
859
860
861
862
863
864
865
866

867
868
869
870
871
872
873
...
945
946
947
948
949
950
951
952
953

954
955
956
957
958
959
960
...
974
975
976
977
978
979
980
981
982

983
984
985
986
987
988
989
...
992
993
994
995
996
997
998
999
1000

1001
1002
1003
1004
1005
1006
1007
....
1084
1085
1086
1087
1088
1089
1090
1091
1092

1093
1094
1095
1096
1097
1098
1099
....
1188
1189
1190
1191
1192
1193
1194

1195
1196
1197
1198
1199
1200
1201
....
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402

1403
1404
1405
1406
1407
1408
1409
....
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514

1515
1516
1517
1518
1519
1520
1521
....
2007
2008
2009
2010
2011
2012
2013
2014


2015


































2016

2017





























































































































































2018
2019
2020
2021
2022
FILE *dbg;

#define MAXBUFFERSIZE 4096

static char errBuf[256];

/*
 * Channel handling procedures 
 */
static Tcl_DriverOutputProc    udpOutput;
static Tcl_DriverInputProc     udpInput;
static Tcl_DriverCloseProc     udpClose;
static Tcl_DriverWatchProc     udpWatch;
static Tcl_DriverGetHandleProc udpGetHandle;
static Tcl_DriverSetOptionProc udpSetOption;
static Tcl_DriverGetOptionProc udpGetOption;

/*
 * Tcl command procedures
 */
int Udp_CmdProc(ClientData, Tcl_Interp *, int, Tcl_Obj *CONST []);
int udpOpen(ClientData , Tcl_Interp *, int , CONST84 char * []);
int udpConf(ClientData , Tcl_Interp *, int , CONST84 char * []);
int udpPeek(ClientData , Tcl_Interp *, int , CONST84 char * []);
................................................................................
static HANDLE waitForSock;
static HANDLE waitSockRead;
static HANDLE sockListLock;
static UdpState *sockList;

#endif /* ! WIN32 */

/*
 * This structure describes the channel type for accessing UDP.
 */
static Tcl_ChannelType Udp_ChannelType = {
    "udp",                 /* Type name.                                    */
    NULL,                  /* Set blocking/nonblocking behaviour. NULL'able */
    udpClose,              /* Close channel, clean instance data            */
    udpInput,              /* Handle read request                           */
    udpOutput,             /* Handle write request                          */
    NULL,                  /* Move location of access point.      NULL'able */
    udpSetOption,          /* Set options.                        NULL'able */
    udpGetOption,          /* Get options.                        NULL'able */
    udpWatch,              /* Initialize notifier                           */
    udpGetHandle,          /* Get OS handle from the channel.               */
};

/*
 * ----------------------------------------------------------------------
 * udpInit
 * ----------------------------------------------------------------------
 */
int
................................................................................
			/* Option found. */
			return 1;
		}
	}
	return 0;
}

/*
 * ----------------------------------------------------------------------
 * udpOpen --
 *
 *  opens a UDP socket and addds the file descriptor to the tcl
 *  interpreter
 * ----------------------------------------------------------------------
 */
int
udpOpen(ClientData clientData, Tcl_Interp *interp,
        int argc, CONST84 char * argv[]) 
{
#ifdef WIN32
    SOCKET sock;
#else
    int sock;
#endif
    char channelName[20];
    UdpState *statePtr;
    uint16_t localport = 0;
    int reuse = 0;
	struct sockaddr_storage addr,sockaddr;
	socklen_t addr_len;
    unsigned long status = 1;
    socklen_t len;
	short ss_family = AF_INET; /* Default ipv4 */ 
	char errmsg[] = "upd_open [remoteport] [ipv6] [reuse]";
	int remaining_options = argc;
	
    if (argc >= 2) {		
		if (hasOption(argc,argv,"reuse")) {
           reuse = 1;
           remaining_options--;
 		}

		if (hasOption(argc,argv,"ipv6")) {
 			ss_family = AF_INET6;
 			remaining_options--;			
 		}
		/* The remaining option must be the port (if specified) */
		if (remaining_options == 2) {
		   if (udpGetService(interp, argv[1], &localport) != TCL_OK) {
				Tcl_SetResult (interp, errmsg, NULL);
				return TCL_ERROR;
		   }
		}
    } 
    memset(channelName, 0, sizeof(channelName));
    
	sock = socket(ss_family, SOCK_DGRAM, 0);
    if (sock < 0) {
        snprintf(errBuf, 255, "failed to create socket");
        errBuf[255] = 0;
        UDPTRACE("%s\n", errBuf);
        Tcl_AppendResult(interp, errBuf, (char *)NULL);
        return TCL_ERROR;
    } 

    /*
     * bug #1477669: avoid socket inheritence after exec
     */

#if HAVE_FLAG_FD_CLOEXEC
    fcntl(sock, F_SETFD, FD_CLOEXEC);
#else
#ifdef WIN32
    if (SetHandleInformation((HANDLE)sock, HANDLE_FLAG_INHERIT, 0) == 0) {
        Tcl_AppendResult(interp, "failed to set close-on-exec bit", NULL);
        return TCL_ERROR;
    }
#endif /* WIN32 */
#endif /* HAVE_FLAG_FD_CLOEXEC */

    if (reuse) {
        int one = 1;
#ifdef SO_REUSEPORT
        if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT,
                       (const char *)&one, sizeof(one)) < 0) {
#else
        if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
                       (const char *)&one, sizeof(one)) < 0) {
#endif
             Tcl_SetObjResult(interp, 
                             ErrorToObj("error setting socket option"));
            closesocket(sock);
            return TCL_ERROR;
        }
    }
     
	memset(&addr, 0, sizeof(addr));
	if (ss_family == AF_INET6) {
		((struct sockaddr_in6 *) &addr)->sin6_family = AF_INET6;
		((struct sockaddr_in6 *) &addr)->sin6_port = localport;
		addr_len = sizeof(struct sockaddr_in6);
	} else {
		((struct sockaddr_in *) &addr)->sin_family = AF_INET;
		((struct sockaddr_in *) &addr)->sin_port = localport;
		addr_len = sizeof(struct sockaddr_in);
	}
	if ( bind(sock,(struct sockaddr *)&addr, addr_len) < 0) {
        Tcl_SetObjResult(interp, 
                         ErrorToObj("failed to bind socket to port"));

        closesocket(sock);
        return TCL_ERROR;
    }

    ioctlsocket(sock, FIONBIO, &status);

    if (localport == 0) {
        len = sizeof(sockaddr);
		getsockname(sock, (struct sockaddr *)&sockaddr, &len);
 		if (ss_family == AF_INET6) {
			localport = ((struct sockaddr_in6 *) &sockaddr)->sin6_port;
		} else {
			localport = ((struct sockaddr_in *) &sockaddr)->sin_port;
		}
    }
    
    UDPTRACE("Open socket %d. Bind socket to port %d\n", 
             sock, ntohs(localport));

    statePtr = (UdpState *) ckalloc((unsigned) sizeof(UdpState));
    memset(statePtr, 0, sizeof(UdpState));
    statePtr->sock = sock;
    sprintf(channelName, "sock" SOCKET_PRINTF_FMT, statePtr->sock);
    statePtr->channel = Tcl_CreateChannel(&Udp_ChannelType, channelName,
                                          (ClientData) statePtr,
                                          (TCL_READABLE | TCL_WRITABLE | TCL_MODE_NONBLOCKING));
    statePtr->doread = 1;
    statePtr->multicast = 0;
    statePtr->groupsObj = Tcl_NewListObj(0, NULL);
    Tcl_IncrRefCount(statePtr->groupsObj);
    statePtr->localport = localport;
	statePtr->ss_family = ss_family;
    Tcl_RegisterChannel(interp, statePtr->channel);
#ifdef WIN32
    statePtr->threadId = Tcl_GetCurrentThread();    
    statePtr->packetNum = 0;
    statePtr->next = NULL;
    statePtr->packets = NULL;
    statePtr->packetsTail = NULL;
#endif
    /* Tcl_SetChannelOption(interp, statePtr->channel, "-blocking", "0"); */
    Tcl_AppendResult(interp, channelName, (char *)NULL);
#ifdef WIN32
    WaitForSingleObject(sockListLock, INFINITE);
    statePtr->next = sockList;
    sockList = statePtr;

    UDPTRACE("Added %d to sockList\n", statePtr->sock);
    SetEvent(sockListLock);
    SetEvent(waitForSock);
#endif
    return TCL_OK;
}

/*
* ----------------------------------------------------------------------
* udpConf --
* ----------------------------------------------------------------------
*/
int
................................................................................
        Tcl_AppendResult(interp, "sockets are not available on this system",
                         NULL);
    }
    return TCL_ERROR;
}

#endif /* ! WIN32 */









/*
 * ----------------------------------------------------------------------
 * udpClose --
 *  Called from the channel driver code to cleanup and close
 *  the socket.
 *
................................................................................
 *  0 if successful, the value of errno if failed.
 *
 * Side effects:
 *  The socket is closed.
 *
 * ----------------------------------------------------------------------
 */
static int 
udpClose(ClientData instanceData, Tcl_Interp *interp)

{
#ifdef _WIN32
    SOCKET sock;
#else
    int sock;
#endif
    int errorCode = 0;
................................................................................
}

/*
 * ----------------------------------------------------------------------
 * udpWatch --
 * ----------------------------------------------------------------------
 */
static void 
udpWatch(ClientData instanceData, int mask)

{
#ifndef WIN32
    UdpState *fsPtr = (UdpState *) instanceData;
    if (mask) {
        UDPTRACE("Tcl_CreateFileHandler\n");
        Tcl_CreateFileHandler(fsPtr->sock, mask,
                              (Tcl_FileProc *) Tcl_NotifyChannel,
................................................................................
 * Results:
 *   Puts the socket into handlePtr and returns TCL_OK;
 *
 * Side Effects:
 *   None
 * ----------------------------------------------------------------------
 */
static int
udpGetHandle(ClientData instanceData, int direction, ClientData *handlePtr)

{
    UdpState *statePtr = (UdpState *) instanceData;
    UDPTRACE("udpGetHandle %ld\n", (long)statePtr->sock);
#ifndef WIN32
    *handlePtr = (ClientData) (intptr_t) statePtr->sock;
#else
    *handlePtr = (ClientData) statePtr->sock;
................................................................................
}

/*
 * ----------------------------------------------------------------------
 * udpOutput--
 * ----------------------------------------------------------------------
 */
static int
udpOutput(ClientData instanceData, CONST84 char *buf, int toWrite, int *errorCode)

{
	UdpState *statePtr = (UdpState *) instanceData;
    int written;
    int socksize;
    struct hostent *name;
    struct sockaddr_in sendaddrv4;
    struct sockaddr_in6 sendaddrv6;
................................................................................
}

/*
 * ----------------------------------------------------------------------
 * udpInput
 * ----------------------------------------------------------------------
 */
static int 
udpInput(ClientData instanceData, char *buf, int bufSize, int *errorCode) 

{
    UdpState *statePtr = (UdpState *) instanceData;
    int bytesRead;

#ifdef WIN32
    PacketList *packets;
#else /* ! WIN32 */
................................................................................
    if (bytesRead > -1) {
        return bytesRead;
    }
    
    *errorCode = errno;
    return -1;
}


/* ---------------------------------------------------------------------- 
 *
 * LSearch --
 *
 * 	Find a string item in a list and return the index of -1.
 */
................................................................................
}
 
/*
* ----------------------------------------------------------------------
* udpGetOption --
* ----------------------------------------------------------------------
*/
static int 
udpGetOption(ClientData instanceData, Tcl_Interp *interp,
			 CONST84 char *optionName, Tcl_DString *optionValue)

{
	UdpState *statePtr = (UdpState *)instanceData;
	CONST84 char * options[] = { "myport", "remote", "peer", "mcastgroups", "mcastloop", "broadcast", "ttl", NULL};
	int r = TCL_OK;
	
	if (optionName == NULL) {
		Tcl_DString ds;
................................................................................
 * ----------------------------------------------------------------------
 * udpSetOption --
 *
 *  Handle channel configuration requests from the generic layer.
 *
 * ----------------------------------------------------------------------
 */
static int
udpSetOption(ClientData instanceData, Tcl_Interp *interp,
             CONST84 char *optionName, CONST84 char *newValue)

{
    UdpState *statePtr = (UdpState *)instanceData;
    CONST84 char * options = "remote mcastadd mcastdrop mcastloop broadcast ttl";
    int r = TCL_OK;
	
    if (!strcmp("-remote", optionName)) {
		r = udpSetRemoteOption(statePtr,interp,(const char *)newValue);
................................................................................
    if (*portPtr > 0xFFFF) {
        Tcl_AppendResult(interp, "couldn't open socket: port number too high",
                         (char *) NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}



/*


































 * ----------------------------------------------------------------------

 *





























































































































































 * Local variables:
 * mode: c
 * indent-tabs-mode: nil
 * End:
 */






<
<
<
<
<
<
<
<
<
<
<







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







>
>
>
>
>
>
>
>







 







|
|
>







 







|
|
>







 







|
|
>







 







|
|
>







 







|
|
>







 







>







 







|
|
|
>







 







|
|
|
>







 








>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>





84
85
86
87
88
89
90











91
92
93
94
95
96
97
...
132
133
134
135
136
137
138















139
140
141
142
143
144
145
...
223
224
225
226
227
228
229




























































































































































230
231
232
233
234
235
236
...
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
...
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
...
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
...
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
...
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
...
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
....
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
....
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
....
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
....
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
FILE *dbg;

#define MAXBUFFERSIZE 4096

static char errBuf[256];












/*
 * Tcl command procedures
 */
int Udp_CmdProc(ClientData, Tcl_Interp *, int, Tcl_Obj *CONST []);
int udpOpen(ClientData , Tcl_Interp *, int , CONST84 char * []);
int udpConf(ClientData , Tcl_Interp *, int , CONST84 char * []);
int udpPeek(ClientData , Tcl_Interp *, int , CONST84 char * []);
................................................................................
static HANDLE waitForSock;
static HANDLE waitSockRead;
static HANDLE sockListLock;
static UdpState *sockList;

#endif /* ! WIN32 */

















/*
 * ----------------------------------------------------------------------
 * udpInit
 * ----------------------------------------------------------------------
 */
int
................................................................................
			/* Option found. */
			return 1;
		}
	}
	return 0;
}






























































































































































/*
* ----------------------------------------------------------------------
* udpConf --
* ----------------------------------------------------------------------
*/
int
................................................................................
        Tcl_AppendResult(interp, "sockets are not available on this system",
                         NULL);
    }
    return TCL_ERROR;
}

#endif /* ! WIN32 */



/*
 * Channel handling procedures
 */



/*
 * ----------------------------------------------------------------------
 * udpClose --
 *  Called from the channel driver code to cleanup and close
 *  the socket.
 *
................................................................................
 *  0 if successful, the value of errno if failed.
 *
 * Side effects:
 *  The socket is closed.
 *
 * ----------------------------------------------------------------------
 */
static int udpClose(
ClientData instanceData, Tcl_Interp *interp
)
{
#ifdef _WIN32
    SOCKET sock;
#else
    int sock;
#endif
    int errorCode = 0;
................................................................................
}

/*
 * ----------------------------------------------------------------------
 * udpWatch --
 * ----------------------------------------------------------------------
 */
static int udpWatch(
ClientData instanceData, int mask
)
{
#ifndef WIN32
    UdpState *fsPtr = (UdpState *) instanceData;
    if (mask) {
        UDPTRACE("Tcl_CreateFileHandler\n");
        Tcl_CreateFileHandler(fsPtr->sock, mask,
                              (Tcl_FileProc *) Tcl_NotifyChannel,
................................................................................
 * Results:
 *   Puts the socket into handlePtr and returns TCL_OK;
 *
 * Side Effects:
 *   None
 * ----------------------------------------------------------------------
 */
static int udpGetHandle(
ClientData instanceData, int direction, ClientData *handlePtr
)
{
    UdpState *statePtr = (UdpState *) instanceData;
    UDPTRACE("udpGetHandle %ld\n", (long)statePtr->sock);
#ifndef WIN32
    *handlePtr = (ClientData) (intptr_t) statePtr->sock;
#else
    *handlePtr = (ClientData) statePtr->sock;
................................................................................
}

/*
 * ----------------------------------------------------------------------
 * udpOutput--
 * ----------------------------------------------------------------------
 */
static int udpOutput(
ClientData instanceData, CONST84 char *buf, int toWrite, int *errorCode
)
{
	UdpState *statePtr = (UdpState *) instanceData;
    int written;
    int socksize;
    struct hostent *name;
    struct sockaddr_in sendaddrv4;
    struct sockaddr_in6 sendaddrv6;
................................................................................
}

/*
 * ----------------------------------------------------------------------
 * udpInput
 * ----------------------------------------------------------------------
 */
static int udpInput(
ClientData instanceData, char *buf, int bufSize, int *errorCode
)
{
    UdpState *statePtr = (UdpState *) instanceData;
    int bytesRead;

#ifdef WIN32
    PacketList *packets;
#else /* ! WIN32 */
................................................................................
    if (bytesRead > -1) {
        return bytesRead;
    }

    *errorCode = errno;
    return -1;
}


/* ----------------------------------------------------------------------
 *
 * LSearch --
 *
 * 	Find a string item in a list and return the index of -1.
 */
................................................................................
}
 
/*
* ----------------------------------------------------------------------
* udpGetOption --
* ----------------------------------------------------------------------
*/
static int udpGetOption(
ClientData instanceData, Tcl_Interp *interp,
CONST84 char *optionName, Tcl_DString *optionValue
)
{
	UdpState *statePtr = (UdpState *)instanceData;
	CONST84 char * options[] = { "myport", "remote", "peer", "mcastgroups", "mcastloop", "broadcast", "ttl", NULL};
	int r = TCL_OK;

	if (optionName == NULL) {
		Tcl_DString ds;
................................................................................
 * ----------------------------------------------------------------------
 * udpSetOption --
 *
 *  Handle channel configuration requests from the generic layer.
 *
 * ----------------------------------------------------------------------
 */
static int udpSetOption(
ClientData instanceData, Tcl_Interp *interp,
CONST84 char *optionName, CONST84 char *newValue
)
{
    UdpState *statePtr = (UdpState *)instanceData;
    CONST84 char * options = "remote mcastadd mcastdrop mcastloop broadcast ttl";
    int r = TCL_OK;

    if (!strcmp("-remote", optionName)) {
		r = udpSetRemoteOption(statePtr,interp,(const char *)newValue);
................................................................................
    if (*portPtr > 0xFFFF) {
        Tcl_AppendResult(interp, "couldn't open socket: port number too high",
                         (char *) NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}



/*
 * This structure describes the channel type for accessing UDP.
 */
static Tcl_ChannelType Udp_ChannelType = {
    "udp",                 /* Type name.                                    */
#ifdef TCL_CHANNEL_VERSION_4
    TCL_CHANNEL_VERSION_4,	/* v5 channel */
    udpClose,              /* Close channel, clean instance data            */
    udpInput,              /* Handle read request                           */
    udpOutput,             /* Handle write request                          */
    NULL,                  /* Seek proc. */
    udpSetOption,          /* Set options.                        NULL'able */
    udpGetOption,          /* Get options.                        NULL'able */
    udpWatch,              /* Initialize notifier                           */
    udpGetHandle,          /* Get OS handle from the channel.               */
    NULL,			/* close2proc */
    NULL,     /* Set blocking/nonblocking behaviour. NULL'able */
    NULL,			/* Flush proc. */
    NULL,			/* Handling of events bubbling up. */
    NULL,	    /* Wide seek proc. */
    NULL,			/* Thread action. */
#else
    NULL,     /* Set blocking/nonblocking behaviour. NULL'able */
    udpClose,              /* Close channel, clean instance data            */
    udpInput,              /* Handle read request                           */
    udpOutput,             /* Handle write request                          */
    NULL,                  /* Seek proc. */
    udpSetOption,          /* Set options.                        NULL'able */
    udpGetOption,          /* Get options.                        NULL'able */
    udpWatch,              /* Initialize notifier                           */
    udpGetHandle,          /* Get OS handle from the channel.               */
#endif
};

/*
 * ----------------------------------------------------------------------
 * udpOpen --
 *
 *  opens a UDP socket and addds the file descriptor to the tcl
 *  interpreter
 * ----------------------------------------------------------------------
 */
int
udpOpen(ClientData clientData, Tcl_Interp *interp,
        int argc, CONST84 char * argv[])
{
#ifdef WIN32
    SOCKET sock;
#else
    int sock;
#endif
    char channelName[20];
    UdpState *statePtr;
    uint16_t localport = 0;
    int reuse = 0;
	struct sockaddr_storage addr,sockaddr;
	socklen_t addr_len;
    unsigned long status = 1;
    socklen_t len;
	short ss_family = AF_INET; /* Default ipv4 */
	char errmsg[] = "upd_open [remoteport] [ipv6] [reuse]";
	int remaining_options = argc;

    if (argc >= 2) {
		if (hasOption(argc,argv,"reuse")) {
           reuse = 1;
           remaining_options--;
 		}

		if (hasOption(argc,argv,"ipv6")) {
 			ss_family = AF_INET6;
 			remaining_options--;
 		}
		/* The remaining option must be the port (if specified) */
		if (remaining_options == 2) {
		   if (udpGetService(interp, argv[1], &localport) != TCL_OK) {
				Tcl_SetResult (interp, errmsg, NULL);
				return TCL_ERROR;
		   }
		}
    }
    memset(channelName, 0, sizeof(channelName));

	sock = socket(ss_family, SOCK_DGRAM, 0);
    if (sock < 0) {
        snprintf(errBuf, 255, "failed to create socket");
        errBuf[255] = 0;
        UDPTRACE("%s\n", errBuf);
        Tcl_AppendResult(interp, errBuf, (char *)NULL);
        return TCL_ERROR;
    }

    /*
     * bug #1477669: avoid socket inheritence after exec
     */

#if HAVE_FLAG_FD_CLOEXEC
    fcntl(sock, F_SETFD, FD_CLOEXEC);
#else
#ifdef WIN32
    if (SetHandleInformation((HANDLE)sock, HANDLE_FLAG_INHERIT, 0) == 0) {
        Tcl_AppendResult(interp, "failed to set close-on-exec bit", NULL);
        return TCL_ERROR;
    }
#endif /* WIN32 */
#endif /* HAVE_FLAG_FD_CLOEXEC */

    if (reuse) {
        int one = 1;
#ifdef SO_REUSEPORT
        if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT,
                       (const char *)&one, sizeof(one)) < 0) {
#else
        if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
                       (const char *)&one, sizeof(one)) < 0) {
#endif
             Tcl_SetObjResult(interp,
                             ErrorToObj("error setting socket option"));
            closesocket(sock);
            return TCL_ERROR;
        }
    }

	memset(&addr, 0, sizeof(addr));
	if (ss_family == AF_INET6) {
		((struct sockaddr_in6 *) &addr)->sin6_family = AF_INET6;
		((struct sockaddr_in6 *) &addr)->sin6_port = localport;
		addr_len = sizeof(struct sockaddr_in6);
	} else {
		((struct sockaddr_in *) &addr)->sin_family = AF_INET;
		((struct sockaddr_in *) &addr)->sin_port = localport;
		addr_len = sizeof(struct sockaddr_in);
	}
	if ( bind(sock,(struct sockaddr *)&addr, addr_len) < 0) {
        Tcl_SetObjResult(interp,
                         ErrorToObj("failed to bind socket to port"));

        closesocket(sock);
        return TCL_ERROR;
    }

    ioctlsocket(sock, FIONBIO, &status);

    if (localport == 0) {
        len = sizeof(sockaddr);
		getsockname(sock, (struct sockaddr *)&sockaddr, &len);
 		if (ss_family == AF_INET6) {
			localport = ((struct sockaddr_in6 *) &sockaddr)->sin6_port;
		} else {
			localport = ((struct sockaddr_in *) &sockaddr)->sin_port;
		}
    }

    UDPTRACE("Open socket %d. Bind socket to port %d\n",
             sock, ntohs(localport));

    statePtr = (UdpState *) ckalloc((unsigned) sizeof(UdpState));
    memset(statePtr, 0, sizeof(UdpState));
    statePtr->sock = sock;
    sprintf(channelName, "sock" SOCKET_PRINTF_FMT, statePtr->sock);
    statePtr->channel = Tcl_CreateChannel(&Udp_ChannelType, channelName,
                                          (ClientData) statePtr,
                                          (TCL_READABLE | TCL_WRITABLE | TCL_MODE_NONBLOCKING));
    statePtr->doread = 1;
    statePtr->multicast = 0;
    statePtr->groupsObj = Tcl_NewListObj(0, NULL);
    Tcl_IncrRefCount(statePtr->groupsObj);
    statePtr->localport = localport;
	statePtr->ss_family = ss_family;
    Tcl_RegisterChannel(interp, statePtr->channel);
#ifdef WIN32
    statePtr->threadId = Tcl_GetCurrentThread();
    statePtr->packetNum = 0;
    statePtr->next = NULL;
    statePtr->packets = NULL;
    statePtr->packetsTail = NULL;
#endif
    /* Tcl_SetChannelOption(interp, statePtr->channel, "-blocking", "0"); */
    Tcl_AppendResult(interp, channelName, (char *)NULL);
#ifdef WIN32
    WaitForSingleObject(sockListLock, INFINITE);
    statePtr->next = sockList;
    sockList = statePtr;

    UDPTRACE("Added %d to sockList\n", statePtr->sock);
    SetEvent(sockListLock);
    SetEvent(waitForSock);
#endif
    return TCL_OK;
}


/*
 * ----------------------------------------------------------------------
 *
 * Local variables:
 * mode: c
 * indent-tabs-mode: nil
 * End:
 */