About Linux Networking Programming - linux

i have written the client and server c file to make an echo server program,i wrote it according to the tutorial video, but i can not figure out where i made the mistakes
//this is the client.c
#include <sys/socket.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <errno.h>
#include <arpa/inet.h>
int main(void)
{
int sock;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
printf("socket establish fail!");
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(30000);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
if(connect(sock, (struct sockaddr*)&servaddr, sizeof(servaddr))<0)
printf("connect failed");
char sendbuf[1024] = { 0 };
char recvbuf[1024] = { 0 };
while (fgets(sendbuf,sizeof(sendbuf),stdin) != NULL)
{
write(sock, sendbuf, sizeof(sendbuf));
read(sock, recvbuf, sizeof(recvbuf));
//fputs(recvbuf, stdout);
printf("%s",recvbuf);
memset(sendbuf, 0, sizeof(sendbuf));
memset(recvbuf, 0, sizeof(recvbuf));
}
close(sock);
return 0;
}
and
//this is the server.c
#include <sys/socket.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <errno.h>
#include <arpa/inet.h>
int main(void)
{
int listenfd, conn;
struct sockaddr_in peeraddr;
struct sockaddr_in servaddr;
socklen_t peerlen = sizeof(peeraddr);
char recvbuf[1024];
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
printf("socket establish fail!");
memset(&servaddr, 0, sizeof(servaddr));
memset(&recvbuf, 0, sizeof(recvbuf));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(30000);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
printf("Bind fail");
if (listen(listenfd, 5) < 0)
printf("Listen fail");
if (conn= accept(listenfd, (struct sockaddr*)&peeraddr, &peerlen) < 0)
printf("accept fail");
while (1)
{
int ret = read(conn, recvbuf, sizeof(recvbuf));
//fputs(recvbuf,stdout);
printf("%s",recvbuf);
write(conn, recvbuf, ret);
}
close(conn);
close(listenfd);
return 0;
}
i worked for it for several hours but i can not find the answer
please help me!

Related

NETLINK_NFLOG support in Linux 4.14

I've this program which runs fine on Linux 2.6.34. While porting this program to 4.14, socket creation is giving error "Error: : Protocol not supported". As per http://man7.org/linux/man-pages/man7/netlink.7.html
NETLINK_NFLOG (up to and including Linux 3.16)
Netfilter/iptables ULOG.
Do we know what is the alternative in 4.14 ?
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <pthread.h>
#include <netinet/ip.h>
#include <linux/types.h>
#include <linux/netlink.h>
int main()
{
struct sockaddr_nl addr;
int mypid;
int status;
int sockfd = -1;
/* mypid = getpid(); */
mypid = pthread_self();
sockfd = socket(AF_NETLINK, SOCK_RAW, NETLINK_NFLOG);
if (sockfd <= 0) {
printf("netlink socket() failed - rc:%d, errno:%d\n",
sockfd, errno);
perror("Error: ");
return (-1);
}
/* set up socket address */
memset(&addr, 0, sizeof (addr));
addr.nl_pid = mypid;
addr.nl_family = AF_NETLINK;
/*
nl_groups is the multicast
group ID to which the ULOG
messages will be sent.It
is bitmap of hexadecimal
format
*/
addr.nl_groups = 1;
/* bind socket to listen on
* multicast group 1 */
status = bind(sockfd, (struct sockaddr *)&addr, sizeof (addr));
if (status < 0) {
perror("bind:");
close(sockfd);
return (-1);
}
printf("socket bind successful\n");
close(sockfd);
return (0);
}
I tried to browse kernel source but couldn't identify.
I've below config
CONFIG_NETFILTER=y
# CONFIG_NETFILTER_ADVANCED is not set
CONFIG_NETFILTER_INGRESS=y
CONFIG_NETFILTER_NETLINK=y
CONFIG_NETFILTER_NETLINK_LOG=y
# CONFIG_NETFILTER_NETLINK_GLUE_CT is not set
CONFIG_NETFILTER_XTABLES=y
CONFIG_NETFILTER_XT_MARK=y
CONFIG_NETFILTER_XT_TARGET_CONNSECMARK=y
CONFIG_NETFILTER_XT_TARGET_LOG=y
CONFIG_NETFILTER_XT_NAT=y
# CONFIG_NETFILTER_XT_TARGET_NETMAP is not set
CONFIG_NETFILTER_XT_TARGET_NFLOG=y
# CONFIG_NETFILTER_XT_TARGET_REDIRECT is not set
CONFIG_NETFILTER_XT_TARGET_SECMARK=y
CONFIG_NETFILTER_XT_TARGET_TCPMSS=y
CONFIG_NETFILTER_XT_MATCH_ADDRTYPE=y
CONFIG_NETFILTER_XT_MATCH_CONNTRACK=y
CONFIG_NETFILTER_XT_MATCH_POLICY=y
CONFIG_NETFILTER_XT_MATCH_STATE=y
NETLINK_NFLOG (up to and including Linux 3.16)
see worked example in libnml

UDP client doesn't connect with server

I create chat with clients and server. But the client can't connect to the server. Please tell me what is wrong?
Server code
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define BUFOR 512
int main(int argc, char *argv[])
{
int fd, serverLength, cLength;
struct sockaddr_in serverAddr, c_addr[2], clientAddr;
cLength = sizeof(clientAddr);
char buf[BUFOR];
int clients = 0;
int c_port[2];
if(argc != 2)
{
printf(" portu");
exit(1);
}
uint16_t port = atoi( argv[ 1 ] );
if ((fd = socket(AF_INET, SOCK_DGRAM, 0))==-1)
{
perror("Blad socket");
exit(1);
}
bzero((char*) &serverAddr, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(port);
serverLength = sizeof(serverAddr);
if (bind(fd, (struct sockaddr* ) &serverAddr, serverLength)==-1)
{
perror("Blad bind");
exit(1);
}
for(;;)
{
printf("Receiving...\n");
if (recvfrom(fd, buf, BUFOR, 0, (struct sockaddr*)&clientAddr, &cLength)==-1)
{
perror("Blad recvfrom");
exit(1);
}
if (clients==0)
{
c_addr[0] = clientAddr;
c_port[0] = ntohs(c_addr[0].sin_port);
clients++;
printf("Client 0 was connected. Port: %d\n",c_port[0]);
sendto(fd, "I am only one cleint.", 24, 0, (struct sockaddr*)&clientAddr, cLength);
}else if(clients==1)
{
if (c_port[0]==ntohs(clientAddr.sin_port))
{
sendto(fd, "I am only one client.", 24, 0, (struct sockaddr*)&c_addr[0], sizeof(c_addr[0]));
printf("One cleint\n");
}else
{
c_addr[1] = clientAddr;
c_port[1] = ntohs(c_addr[1].sin_port);
clients++;
printf("Second cleint\n");
sendto(fd, buf, BUFOR, 0, (struct sockaddr*)&c_addr[0], sizeof(c_addr[0]));
}
}else
{
if (c_port[0]==ntohs(clientAddr.sin_port))
{
printf("Sending emssage for client 1\n");
if (sendto(fd, buf, BUFOR, 0, (struct sockaddr*)&c_addr[1], sizeof(c_addr[0]))==-1)
{
clients--;
perror("Error senttoen");
}
}else
{
printf("Sending message for client 0\n");
if (sendto(fd, buf, BUFOR, 0, (struct sockaddr*)&c_addr[0], sizeof(c_addr[1]))==-1)
{
clients--;
perror("Blad senttoen");
}
}
}
}
close(fd);
return 0;
}
Client code
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <signal.h>
#define BUFLEN 512
int main(int argc, char *argv[])
{
struct sockaddr_in serv_addr;
int sockfd;
socklen_t slen;
slen=sizeof(serv_addr);
char buf[BUFLEN];
if(argc != 3)
{
printf("Usage : %s <Server-IP>\n",argv[2]);
exit(0);
}
if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
{
perror("Socket Error");
exit(1);
}
uint16_t port = atoi( argv[ 1 ] );
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
serv_addr.sin_addr.s_addr = inet_addr(argv[2]);
while(1)
{
bzero(buf,BUFLEN);
printf("Attempting to READ to socket %d: ",sockfd);
fflush(stdout);
if(recvfrom(sockfd, buf, BUFLEN, 0, (struct sockaddr*)&serv_addr, &slen)==-1)
{
perror("Blad bind");
exit(1);
}
printf("The message from the server is: %s \n",buf);
printf("Please enter the message to send: ");
bzero(buf,BUFLEN);
fgets(buf,BUFLEN,stdin);
printf("Attempting to write to socket %d: ",sockfd);
fflush(stdout);
if (sendto(sockfd, buf, BUFLEN, 0, (struct sockaddr*)&serv_addr, slen)==-1)
{
perror("Blad bind");
exit(1);
}
}
close(sockfd);
return 0;
}
It seems the sendto is blocked by recvfrom, but I don't know how to create it in infinitable loop.

Example code on using PACKET_QDISC_BYPASS option on ethernet raw socket on linux

According to http://man7.org/linux/man-pages/man7/packet.7.html, there is a new option
PACKET_QDISC_BYPASS since linux 3.14. This has the potential of sending and receiving packets a lot faster.
Saw a sample code: https://github.com/netoptimizer/network-testing/blob/master/src/raw_packet_send.c, but unfortunately it doesn't have the code on sending packets.
I added some code to send packets but it has a problem with sendto.
# ./raw_packet_send p6p1 64
Lame RAW/PF_PACKET socket TX test program
Enabled kernel qdisc bypass
error sendto : Invalid argument
Not sure why. Here is the code (original raw_packet_send.c with my silly code). Please let me know how could make it work or point me to some good simple sample code. Thanks.
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/if_packet.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
//#include <stdio.h>
//#include <sys/types.h>
//#include <sys/stat.h>
//#include <sys/socket.h>
//#include <sys/mman.h>
//#include <linux/filter.h>
//#include <ctype.h>
//#include <fcntl.h>
//#include <unistd.h>
//#include <bits/wordsize.h>
//#include <net/ethernet.h>
//#include <netinet/ip.h>
//#include <arpa/inet.h>
//#include <stdint.h>
//#include <string.h>
//#include <assert.h>
//#include <net/if.h>
//#include <inttypes.h>
//#include <poll.h>
//#include <unistd.h>
#ifndef PACKET_QDISC_BYPASS
#define PACKET_QDISC_BYPASS 20
#endif
#include "common_socket.h"
char pkt[2000] = {0x00, 1,2,3,4,0, 0,1,2,3,4,1, 8, 0};;
int len = 96;
char intfName[100] = "em1";
/* Avail in kernel >= 3.14
* in commit d346a3fae3 (packet: introduce PACKET_QDISC_BYPASS socket option)
*/
void set_sock_qdisc_bypass(int fd, int verbose)
{
int ret, val = 1;
ret = setsockopt(fd, SOL_PACKET, PACKET_QDISC_BYPASS, &val, sizeof(val));
if (ret < 0) {
printf("[DEBUG] %s(): err:%d errno:%d\n", __func__, ret, errno);
if (errno == ENOPROTOOPT) {
if (verbose)
printf("No kernel support for PACKET_QDISC_BYPASS"
" (kernel < 3.14?)\n");
} else {
perror("Cannot set PACKET_QDISC_BYPASS");
}
} else
if (verbose) printf("Enabled kernel qdisc bypass\n");
}
int pf_tx_socket(int ver)
{
int ret, val = 1;
/* Don't use proto htons(ETH_P_ALL) as we only want to transmit */
int sock = socket(PF_PACKET, SOCK_RAW, 0);
//int sock = socket(AF_INET,SOCK_PACKET,htons(3));
if (sock == -1) {
perror("Creation of RAW PF_SOCKET failed!\n");
exit(1);
}
ret = Setsockopt(sock, SOL_PACKET, PACKET_VERSION, &ver, sizeof(ver));
return sock;
}
void mybind(int sock, char *intf) {
struct ifreq ifr;
int rc;
memset((char*)&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), intf);
if ((rc = setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr))) < 0)
{
perror("Server-setsockopt() error for SO_BINDTODEVICE");
printf("%s\n", strerror(errno));
close(sock);
exit(-1);
}
}
int flood (int sock) {
struct sockaddr intfAddrs;
char cmd[100];
int tmp;
memset((char*)&intfAddrs, 0, sizeof (struct sockaddr));
intfAddrs.sa_family = PF_PACKET;
strcpy((char*)(intfAddrs.sa_data), intfName);
sprintf(cmd, "ifconfig %s promisc", intfName); system(cmd);
while (1) {
while (1) {
tmp = sendto(sock, pkt, len, 0, &intfAddrs, sizeof(intfAddrs));
if (tmp != len) {perror("error sendto "); exit(0); }
}
}
}
int main(int argc, char **argv)
{
if (argc > 1) { strcpy(intfName, argv[1]); }
if (argc > 2) { len = atoi(argv[2]); }
printf("Lame RAW/PF_PACKET socket TX test program\n");
int sock = pf_tx_socket(0);
set_sock_qdisc_bypass(sock, 1);
mybind(sock, intfName);
flood(sock);
return 0;
}
I think you need to change from PF_PACKET to AF_PACKET (although it looks like PF_PACKET is an alias to AF_PACKET) but I don't have any success when using PF_PACKET.
This code works for me:
// Create a raw socket
sock_fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (sock_fd == -1) {
perror("Can't create AF_PACKET socket");
return EXIT_FAILURE;
}
// Check kernel version
static const int32_t sock_qdisc_bypass = 1;
int32_t sock_qdisc_ret = setsockopt(thd_opt->sock_fd, SOL_PACKET, PACKET_QDISC_BYPASS, &sock_qdisc_bypass, sizeof(sock_qdisc_bypass));
if (sock_qdisc_ret == -1) {
perror("Can't enable QDISC bypass on socket");
return EXIT_FAILURE;
}
This is from setup_socket_mmap() here

Why does tcpdump enable this code to work?

I have a small network consisting of 2 hosts (OS X and linux) with a switch between them. When I run the following pair of programs, the receiver (linux) doesn't see any multicast packets. However, when I run
tcpdump -i eth0 -s 512 udp
on the linux box, everything starts to work. Can someone tell me why running tcpdump enables this to work?
Note that both machines have IPv6 enabled (if that matters). The host addresses in the code are the IPv4 addresses of the local interfaces.
On the OS X machine, I run:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define BUFLEN 256
int s;
int count;
struct in_addr local_address;
struct sockaddr_in multicast_address;
char buffer[BUFLEN];
int
main (int argc, char *argv[]) {
int port = 12345;
int retval = 0;
char *host_ip = "192.168.1.31";
char *multicast_ip = "224.0.0.251";
count = (int)time(NULL);
s = socket(AF_INET, SOCK_DGRAM, 0);
printf("s=%d\n", s);
local_address.s_addr = inet_addr(host_ip);
retval = setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, (char *)&local_address, sizeof(local_address));
printf("setsockopt=%d\n", retval);
memset((char *)&multicast_address, 0, sizeof(multicast_address));
multicast_address.sin_family = AF_INET;
multicast_address.sin_addr.s_addr = inet_addr(multicast_ip);
multicast_address.sin_port = htons(port);
while (1) {
sprintf(buffer, "Message number %d", count);
count++;
retval = sendto(s, buffer, BUFLEN, 0, (struct sockaddr*)&multicast_address, sizeof(multicast_address));
printf("sendto=%d\n", retval);
sleep(3);
}
return 0;
}
On the linux box, I run:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define BUFLEN 256
int s;
struct ip_mreq multicast_group;
struct sockaddr_in localSock;
char buffer[BUFLEN];
int
main(int argc, char *argv[]) {
int reuse = 1;
int retval = 0;
int port = 12345;
char *host_ip = "192.168.1.131";
char *multicast_ip = "224.0.0.251";
s = socket(AF_INET, SOCK_DGRAM, 0);
printf("s = %d\n", s);
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse));
printf("REUSEADDR = %d\n", retval);
memset((char *) &localSock, 0, sizeof(localSock));
localSock.sin_family = AF_INET;
localSock.sin_port = htons(port);
localSock.sin_addr.s_addr = INADDR_ANY;
retval = bind(s, (struct sockaddr*)&localSock, sizeof(localSock));
printf("bind = %d\n", retval);
multicast_group.imr_multiaddr.s_addr = inet_addr(multicast_ip);
multicast_group.imr_interface.s_addr = inet_addr(host_ip);
retval = setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&multicast_group, sizeof(multicast_group));
printf("ADD_MEMBERSHIP = %d\n", retval);
while (1) {
retval = read(s, buffer, BUFLEN);
printf("%d => [%s]\n", retval, buffer);
}
return 0;
}
Thanks.

Linux sockets communicating with QTcpSockets in Qt 4

I am trying to communicate with TCP between a Qt program and a regular linux program. I have an existing linux client server program and I am trying to replace the server program with a Qt application. Here is the linux client code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
portno = 9876;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
printf("ERROR opening socket");
return -1;
}
server = gethostbyname("localhost");
if (server == NULL)
{
printf("ERROR, no such host\n");
return -1;
}
memset((char *) &serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
connect(sockfd,(sockaddr*)&serv_addr,sizeof(serv_addr));
sprintf(buffer,"This is a test\n");
n = write(sockfd,buffer,256);
return 0;
}
Here is the qt code
#include <Qt>
#include <QApplication>
#include <QTcpServer>
#include <QMessageBox>
#include <QTcpSocket>
#include <QtNetwork>
#include "qtserver.h"
Server::Server()
{
tcp = new QTcpServer(this);
tcp->listen(QHostAddress::Any,9876);
QObject::connect(tcp,SIGNAL(newConnection()),this,SLOT(printline()));
}
void Server::printline()
{
QTcpSocket *client = tcp->nextPendingConnection();
QObject::connect(client,SIGNAL(disconnected()),
client,SLOT(deleteLater()));
QDataStream in(client);
in.setVersion(QDataStream::Qt_4_0);
QString data;
in >> data;
printf("String = %s\n",(char*)data.data());
}
int main(int argc,char** argv)
{
QApplication a(argc,argv);
Server* server = new Server();
return a.exec();
}
When i try to run both of them I just get "String = " instead of the string outputting. Any idea what I'm doing wrong?
QString::data() returns QChar*, you can't just cast it to char* and hope that it would always work. For debugging QString, use qPrintable instead.
Also, QTcpSocket is very easy to use. Still, instead of writing the code from scratch, why not start by checkout out the examples, e.g. Fortune Server example.

Resources