Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <sys/socket.h>
- #include <arpa/inet.h>
- #include <poll.h>
- #include <fcntl.h>
- #include <errno.h>
- #include "helper.h"
- #define PORT 8080
- int main() {
- int sock = 0, valread;
- struct sockaddr_in serv_addr;
- struct message msg;
- // Create socket
- if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
- perror("socket failed");
- exit(EXIT_FAILURE);
- }
- // Set socket to non-blocking mode
- int flags = fcntl(sock, F_GETFL, 0);
- if (flags == -1) {
- perror("fcntl failed");
- exit(EXIT_FAILURE);
- }
- if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) == -1) {
- perror("fcntl failed");
- exit(EXIT_FAILURE);
- }
- // Set up server address
- serv_addr.sin_family = AF_INET;
- serv_addr.sin_port = htons(PORT);
- if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
- perror("inet_pton failed");
- exit(EXIT_FAILURE);
- }
- // Connect to server
- if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
- if (errno != EINPROGRESS) {
- perror("connect failed");
- exit(EXIT_FAILURE);
- }
- }
- // Use poll to wait for connection
- struct pollfd fds[1];
- fds[0].fd = sock;
- fds[0].events = POLLOUT;
- if (poll(fds, 1, -1) <= 0) {
- perror("poll failed");
- exit(EXIT_FAILURE);
- }
- if (!(fds[0].revents & POLLOUT)) {
- perror("connect failed");
- exit(EXIT_FAILURE);
- }
- // Receive message from server
- while ((valread = read(sock, &msg, sizeof(msg))) == -1 && errno == EAGAIN);
- if (valread == -1) {
- perror("read failed");
- exit(EXIT_FAILURE);
- }
- printf("ID: %d\n", msg.id);
- printf("Data: %s\n",msg.data);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement