Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 54 lines (42 sloc) 1.399 kB
dd88510 @cibomahto Single port version of a c++ UDP listener.
cibomahto authored
1 #include <iostream>
4bdf1d7 @cibomahto Works on linux, spits characters randomly on os x.
cibomahto authored
2 #include <cstdio>
3 #include <cstring>
4 #include <cstdlib>
dd88510 @cibomahto Single port version of a c++ UDP listener.
cibomahto authored
5
6 #include <sys/socket.h>
7 #include <netinet/in.h>
8 #include <arpa/inet.h>
9
10 #include "SocketListener.h"
11
12 void SocketListener::Connect(std::string ip_address, unsigned int port) {
13 struct sockaddr_in address;
14
15 m_fd = socket(AF_INET, SOCK_DGRAM, 0);
16 if (m_fd < 0)
17 {
18 perror("open_socket: Unable to open socket");
19 exit(1); // TODO: Should we actually exit here?
20 }
21
22
23 address.sin_family = AF_INET;
24 address.sin_port = htons(port);
25 inet_aton(ip_address.c_str(), &address.sin_addr);
26
27 int return_code;
28 return_code = bind(m_fd, (struct sockaddr*) &address, sizeof(struct sockaddr_in));
29 if (return_code < 0)
30 {
31 perror("open_socket: Unable to bind to port");
32 exit(1); // TODO: Should we actually exit here?
33 }
34 }
35
36 int SocketListener::GetFrame(char* frame, int length) {
37 int received_length = read(m_fd, frame, length);
38
39 // TODO: How to return erros here?
40 if (length != received_length) {
41 std::cerr << "Bad data frame, expected_length=" << length
42 << " received_length=" << received_length << std::endl;
43 return -1;
44 }
45
46 if (frame[0] != 0x01) {
47 std::cerr << "Bad header, expected=1"
48 << " got=" << static_cast<int>(frame[0]) << std::endl;
49 return -2;
50 }
51
52 return 0;
53 }
Something went wrong with that request. Please try again.