4 static int winsock_init(void) {
5 WORD wVersionRequested;
9 wVersionRequested = MAKEWORD( 2, 2 );
11 err = WSAStartup( wVersionRequested, &wsaData );
13 /* Tell the user that we could not find a usable */
18 /* Confirm that the WinSock DLL supports 2.2.*/
19 /* Note that if the DLL supports versions greater */
20 /* than 2.2 in addition to 2.2, it will still return */
21 /* 2.2 in wVersion since that is the version we */
24 if ( LOBYTE( wsaData.wVersion ) != 2 ||
25 HIBYTE( wsaData.wVersion ) != 2 ) {
26 /* Tell the user that we could not find a usable */
35 int firmnet_connect_tcp(const char *host, uint16_t port)
39 struct sockaddr_in sin;
46 memset(&sin, 0, sizeof(sin));
47 sin.sin_family = AF_INET;
48 sin.sin_port = htons(port);
50 if ((phe = gethostbyname(host)))
51 memcpy(&sin.sin_addr, phe->h_addr, phe->h_length);
52 else if((sin.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE) {
53 fprintf(stderr, "cannot get host entry for %s", host);
57 ppe = getprotobyname("tcp");
58 ERRNO_CHECK_RETURN(s = socket(PF_INET, SOCK_STREAM, ppe->p_proto), <, 0, -1);
59 ERRNO_CHECK_RETURN(connect(s, (struct sockaddr *) &sin, sizeof(sin)), <, 0, -1);
64 void firmnet_close_socket(int fd) {
73 * Send message of size @p n from buffer @p buf to file descriptor @p fd.
74 * @param fd The file descriptor, the message should be send to.
75 * @param buf The buffer containing the message
76 * @param n The length of the message.
77 * @return Number of bytes written or -1 on failure.
79 ssize_t firmnet_send(int fd, const void *buf, size_t n)
82 size_t bytes_written = 0;
83 const char *data = buf;
86 res = send(fd, &data[bytes_written], n - bytes_written, 0);
95 } while (bytes_written < n);
101 * Try to read some bytes but block until a certain amount is read.
102 * @param fd The file descriptor.
103 * @param buf The buffer to read into.
104 * @param try The amount of bytes to try to read.
105 * @param at_least block until this many bytes are read.
106 * @return The number of bytes read or -1 on error.
108 ssize_t firmnet_recv(int fd, void *buf, size_t try, size_t at_least)
111 size_t bytes_read = 0;
115 res = recv(fd, &data[bytes_read], try - bytes_read, 0);
117 if (res == 0 || errno != EAGAIN)
124 } while (bytes_read < at_least);