Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Berkeley sockets
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===Server=== An application may set up a UDP server on port number 7654 as follows. The programs contains an infinite loop that receives UDP datagrams with function ''recvfrom()''. <syntaxhighlight lang="c" highlight="32,25,24"> #include <stdio.h> #include <errno.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <unistd.h> /* for close() for socket */ #include <stdlib.h> int main(void) { int sock; struct sockaddr_in sa; char buffer[1024]; ssize_t recsize; socklen_t fromlen; memset(&sa, 0, sizeof sa); sa.sin_family = AF_INET; sa.sin_addr.s_addr = htonl(INADDR_ANY); sa.sin_port = htons(7654); fromlen = sizeof sa; sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if (bind(sock, (struct sockaddr *)&sa, sizeof sa) == -1) { perror("error bind failed"); close(sock); exit(EXIT_FAILURE); } for (;;) { recsize = recvfrom(sock, (void*)buffer, sizeof buffer, 0, (struct sockaddr*)&sa, &fromlen); if (recsize < 0) { fprintf(stderr, "%s\n", strerror(errno)); exit(EXIT_FAILURE); } printf("recsize: %d\n ", (int)recsize); sleep(1); printf("datagram: %.*s\n", (int)recsize, buffer); } } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)