00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035 #ifndef lint
00036 static const char rcsid[] =
00037 "@(#) $Header: /nfs/jade/vint/CVSROOT/ns-2/emulate/net.cc,v 1.8 2005/01/25 23:29:12 haldar Exp $ (LBL)";
00038 #endif
00039
00040 #include <stdlib.h>
00041 #include <math.h>
00042 #ifndef WIN32
00043 #include <unistd.h>
00044 #endif
00045 #include <stdio.h>
00046 #include <stdlib.h>
00047 #include <fcntl.h>
00048 #include <errno.h>
00049 #include <string.h>
00050 #ifdef WIN32
00051 #include <windows.h>
00052 #include <winsock.h>
00053 #else
00054 #include <sys/socket.h>
00055 #include <sys/uio.h>
00056 #include <sys/time.h>
00057 #endif
00058 #include "net.h"
00059
00060
00061
00062
00063 #if defined(__linux__) || defined(WIN32)
00064 #define MAXPACKETSIZE (1500-28)
00065
00066
00067
00068
00069
00070
00071
00072
00073
00074
00075
00076
00077
00078
00079
00080
00081
00082
00083
00084
00085
00086
00087 #endif
00088
00089 int Network::command(int argc, const char*const* argv)
00090 {
00091 if (argc == 2) {
00092 Tcl& tcl = Tcl::instance();
00093 if (strcmp(argv[1], "flush") == 0) {
00094 if (mode_ == O_RDWR || mode_ == O_RDONLY) {
00095 unsigned char buf[1024];
00096 sockaddr from;
00097 double ts;
00098 while (recv(buf, sizeof(buf), from, ts) > 0)
00099 ;
00100 }
00101 return (TCL_OK);
00102 }
00103 if (strcmp(argv[1], "mode") == 0) {
00104 tcl.result(modename(mode_));
00105 return (TCL_OK);
00106 }
00107 }
00108 return (TclObject::command(argc, argv));
00109 }
00110
00111 int
00112 Network::nonblock(int fd)
00113 {
00114 #ifdef WIN32
00115 u_long flag = 1;
00116 if (ioctlsocket(fd, FIONBIO, &flag) == -1) {
00117 fprintf(stderr,
00118 "Network::nonblock(): ioctlsocket: FIONBIO: %lu\n",
00119 GetLastError());
00120 return -1;
00121 }
00122 #else
00123 int flags;
00124 if ((flags = fcntl(fd, F_GETFL, 0)) < 0) {
00125 perror("Network::nonblock(): fcntl");
00126 return (-1);
00127 }
00128 #if defined(hpux) || defined(__hpux)
00129 flags |= O_NONBLOCK;
00130 #else
00131 flags |= O_NONBLOCK|O_NDELAY;
00132 #endif
00133 if (fcntl(fd, F_SETFL, flags) == -1) {
00134 perror("Network::nonblock(): fcntl: F_SETFL");
00135 return -1;
00136 }
00137 #endif
00138 return 0;
00139 }
00140
00141 int
00142 Network::parsemode(const char *mname)
00143 {
00144 if (strcmp(mname, "readonly") == 0) {
00145 return (O_RDONLY);
00146 } else if (strcmp(mname, "readwrite") == 0) {
00147 return (O_RDWR);
00148 } else if (strcmp(mname, "writeonly") == 0) {
00149 return (O_WRONLY);
00150 }
00151 return (::atoi(mname));
00152 }
00153
00154 char *
00155 Network::modename(int mode)
00156 {
00157 switch (mode) {
00158 case O_RDONLY:
00159 return ("readonly");
00160 case O_WRONLY:
00161 return ("writeonly");
00162 case O_RDWR:
00163 return ("readwrite");
00164 }
00165 return ("unknown");
00166 }