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!
===Client=== The following is a client program for sending a UDP packet containing the string "Hello World!" to address 127.0.0.1 at port number 7654. <syntaxhighlight lang="c" highlight="40"> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <unistd.h> #include <arpa/inet.h> int main(void) { int sock; struct sockaddr_in sa; int bytes_sent; char buffer[200]; strcpy(buffer, "hello world!"); /* create an Internet, datagram, socket using UDP */ sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock == -1) { /* if socket failed to initialize, exit */ printf("Error Creating Socket"); exit(EXIT_FAILURE); } /* Zero out socket address */ memset(&sa, 0, sizeof sa); /* The address is IPv4 */ sa.sin_family = AF_INET; /* IPv4 addresses is a uint32_t, convert a string representation of the octets to the appropriate value */ sa.sin_addr.s_addr = inet_addr("127.0.0.1"); /* sockets are unsigned shorts, htons(x) ensures x is in network byte order, set the port to 7654 */ sa.sin_port = htons(7654); bytes_sent = sendto(sock, buffer, strlen(buffer), 0,(struct sockaddr*)&sa, sizeof sa); if (bytes_sent < 0) { printf("Error sending packet: %s\n", strerror(errno)); exit(EXIT_FAILURE); } close(sock); /* close the socket */ return 0; } </syntaxhighlight> In this code, ''buffer'' is a pointer to the data to be sent, and ''buffer_length'' specifies the size of the data.
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)