Last active
March 19, 2017 08:54
-
-
Save StevenJL/ce136932e05a502304c0710123985236 to your computer and use it in GitHub Desktop.
sock_programming/connect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| int tcp_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); | |
| // AF_INET to create a IPv4 socket | |
| // SOCK_STREAM to use a stream-based protocol | |
| // IPPROTO_TCP to use the TCP protocol | |
| // if tcp_sock is -1, the socket failed to create | |
| if (tcp_sock < 0) { | |
| fputs("socket creation failed", stderr); | |
| exit(1); | |
| } | |
| // we create a struct to store ip address data; | |
| struct sockaddr_in address_info; | |
| // zero out the data in the struct | |
| memset(&address_info, 0, sizeof(address_info)); | |
| // set the address family to be an internet address | |
| address_info.sin_family = AF_INET; | |
| char ip_address[] = "123.456.789.101"; | |
| // `inet_pton` converts an ip address from a string representation into a | |
| // 32-bit binary representation and puts it in the ip_address_info struct | |
| int ip_convert_status = inet_pton(AF_INET, ip_address, &address_info.sin_addr.s_addr); | |
| if (ip_convert_status == 0) { | |
| fputs("invalid ip address string", stderr); | |
| exit(1); | |
| } else if (ip_convert_status < 0) { | |
| fputs("inet_pton() failed", stderr); | |
| exit(1); | |
| } | |
| in_port_t port = 42; | |
| // `htons` stands for "host to network short" and converts a port number to | |
| // the binary value format required by the socket api. | |
| address_info.sin_port = htons(port); | |
| // `connect` establishes a connection between a given socket and the ip address | |
| // and port specified by the given sockaddr_in struct. Note that we needed to | |
| // cast a sockaddr_in struct to sockaddr struct. | |
| if (connect(tcp_sock, (struct sockaddr*) &address_info, sizeof(address_info)) < 0) { | |
| fputs("connect() failed", stderr); | |
| exit(1); | |
| } | |
| char *data_str = "Here's some data"; | |
| size_t data_str_len = strlen(data_str); | |
| // `send` sends the data to the ip address and port connected to the given socket. | |
| // It returns the number of bytes sent. | |
| ssize_t bytes_sent = send(tcp_sock, data_str, data_str_len, 0); | |
| if (bytes_sent < 0) { | |
| fputs("send() failed", stderr); | |
| exit(1); | |
| } else if (bytes_sent != data_str_len){ | |
| fputs("send() sent unexpected number of bytes", stderr); | |
| exit(1); | |
| } | |
| // `close` lets the socket know that communication has ended, and deallocates | |
| // local resources of the socket. | |
| close(tcp_sock); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment