Created
June 27, 2018 13:29
-
-
Save atomass/fadbc33039aa22991cfef1ea65ae9334 to your computer and use it in GitHub Desktop.
QTcpSocket with specific source/local port
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
// UNIX includes | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
#include <errno.h> | |
#include <string.h> | |
// QT includes | |
#include <QCoreApplication> | |
#include <QTcpSocket> | |
// C++ | |
#include <iostream> | |
#define SRC_PORT 12345 | |
#define DST_PORT 80 | |
#define HOST "www.google.com" | |
int socket_descriptor = -1; | |
bool createSocket() | |
{ | |
socket_descriptor = socket(AF_INET, SOCK_STREAM, 0); | |
return (socket_descriptor > 0); | |
} | |
bool bindSocket() | |
{ | |
struct sockaddr_in src_addr; | |
memset(&src_addr, 0, sizeof(src_addr)); | |
src_addr.sin_family = AF_INET; | |
src_addr.sin_addr.s_addr = htonl(INADDR_ANY); | |
src_addr.sin_port = htons(SOURCE_PORT); | |
int res = bind(socket_descriptor, (struct sockaddr *) &src_addr, sizeof(src_addr)); | |
return (res >= 0); | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
QCoreApplication app(argc, argv); | |
QTcpSocket qt_socket; | |
if ( createSocket() ) | |
{ | |
if ( bindSocket() ) { | |
// emit connectionok | |
qt_socket.setSocketDescriptor(socket_descriptor, QAbstractSocket::SocketState::BoundState); | |
qt_socket.connectToHost(HOST, DST_PORT); | |
} else | |
std::cout << "Error while creating socket: " << strerror(errno) << std::endl; | |
} else | |
std::cout << "Error while creating socket: " << strerror(errno) << std::endl; | |
return app.exec(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using QT_VERSION > 5 this can be achieved with