MSVC 10.0 c vs c++ differences - visual-c++

I'm having difficulty compiling the C program below, It's just the begining of me trying to understand winsock.
The issue is that when compiling the program client.c, I get an error (C2143) missing ';' before 'type'
But when I re-name the source file to 'client.cpp' the program compiles with no errors or warnings.
I don't understand the syntax error that is an error in C but not C++.
#define WIN32_LEAN_AND_MEAN
#define DEBUG
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define PORT "12186"
#define BUFFERLEN 512
int main(int argc, char* argv[])
{
/*
Variable Declorations
*/
WSADATA wsaData;
SOCKET ConnectionSocket = INVALID_SOCKET;
struct addrinfo *result = NULL, *ptr = NULL, hints;
int addrResult;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC; //unspecified so we can be compatible with IPv4 and IPv6
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
#ifdef DEBUG
printf("IPPROTO_TCP: %d", IPPROTO_TCP);
#endif
//Buffers
char * sendbuffer; // Error C2143
char recievebuffer [BUFFERLEN]; //Error C2143
//Initialize Winsock
addrResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if(addrResult !=0)
{
printf("WSAStartup failed: %d", addrResult);
}
addrResult = getaddrinfo(argv[1], PORT, &hints, &result);
if(addrResult != 0)
{
printf("getaddrinfo failed: %d", addrResult);
WSACleanup();
return 1;
}
return 0;
}
Edit:
C variable declorations have to go before all other code in MSVC C functions.
Problem solved.
Is this a C89 thing or is it just MSVC?

The problem might be the place where variable declarations are going. Place them at the beginning of the function with the other variables.
See the last example from MSDN that can cause this error code.

The C compiler which ships with VS only implements C89 (seriously...), so you must declare all of your variables at the top of a given function.

Related

Crash system when the module is running

I need to write a module that creates a file and outputs an inscription with a certain frequency. I implemented it. But when this module is running, at some point the system crashes and no longer turns on.
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/kernel.h>
#include <linux/timer.h>
MODULE_LICENSE("GPL");
#define BUF_LEN 255
#define TEXT "Hello from kernel mod\n"
int g_timer_interval = 10000;
static struct file *i_fp;
struct timer_list g_timer;
loff_t offset = 0;
char buff[BUF_LEN + 1] = TEXT;
void timer_rest(struct timer_list *timer)
{
mod_timer(&g_timer, jiffies + msecs_to_jiffies(g_timer_interval));
i_fp = filp_open("/home/hajol/Test.txt", O_RDWR | O_CREAT, 0644);
kernel_write(i_fp, buff, strlen(buff), &offset);
filp_close(i_fp, NULL);
}
static int __init kernel_init(void)
{
timer_setup(&g_timer, timer_rest, 0);
mod_timer(&g_timer, jiffies + msecs_to_jiffies(g_timer_interval));
return 0;
}
static void __exit kernel_exit(void)
{
pr_info("Ending");
del_timer(&g_timer);
}
module_init(kernel_init);
module_exit(kernel_exit);
When the system crashes, you should get a very detailed error message from the kernel, letting you know where and why this happened (the "oops" message):
Read that error message
Read it again
Understand what it means (this often requires starting over from step 1 a couple of times :-) )
One thing that jumps out at me is that you're not going any error checking on the return value of filp_open. So you could very well be feeding a NULL pointer (or error pointer) into kernel_write.

error:argument type 'xx' is incomplete for hiding call to ptrace example code

I'm testing an antidebug solution with ptrace method; and i compile the program by using ndk21e cross-compile.
The problem is that it compiles successfully with gcc, but fails with ndk cross-compile.
ndk cross-compile compiles all other programs without problems
#include <stdlib.h>
#include <stdio.h>
#include<sys/ptrace.h>
#include <dlfcn.h>
#include <string.h>
int main(int argc, char **argv) {
void *handle;
long (*go)(enum __ptrace_request request, pid_t pid);
// get a handle to the library that contains 'ptrace'
handle = dlopen ("/lib/x86_64-linux-gnu/libc.so.6", RTLD_LAZY);
// reference to the dynamically-resolved function 'ptrace'
go = dlsym(handle, "ptrace");
if (go(PTRACE_TRACEME, 0) < 0) {
puts("being traced");
exit(1);
}
puts("not being traced");
// cleanup
dlclose(handle);
return 0;
}
And it shows the error like the picture as follow:
gcc compileresult and cross-compile error result
How can i solve this problem. Thanks.

setsockopt IPT_SO_SET_REPLACE flag return error (linux)

I try to use setsockopt with the flag IPT_SO_SET_REPLACE but i keep getting the wired error from errno Protocol not available this is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sched.h>
#include <linux/sched.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include <unistd.h>
#include <sys/ptrace.h>
#include <netinet/in.h>
#include <net/if.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include <fcntl.h>
int main(void) {
int sock;
int ret;
void *data;
size_t size;
struct ipt_replace *repl;
sock = socket(PF_INET, SOCK_RAW, IPPROTO_RAW);
if (sock == -1) {
perror("socket");
return -1;
}
size = sizeof(struct ipt_replace);
data = malloc(size); Protocol not available
if (data == NULL) {
perror("malloc");
return -1;
}
memset(data, 0, size);
repl = (struct ipt_replace *) data;
repl->num_counters = 0x1;
repl->size = 0xffffffff;
repl->valid_hooks = 0x1;
repl->num_entries = 0x1;
ret = setsockopt(sock, SOL_IP, IPT_SO_SET_REPLACE, (void *) data, size);
printf("\ndone %d\n", ret);
perror("error: ");
return 0;
}
this is the output :
sock:3
data:
size:92
done -1
error: : Protocol not available
Looking briefly at the kernel code, this would seem to indicate that the IP tables module isn't available (i.e. the kernel wasn't built with it configured, or it can't be found or loaded).
It appears to me that for a socket of the kind you created, the code flow is:
enter raw_setsockopt: level != SOL_RAW so...
call ip_setsockopt: level == SOL_IP but option isn't any of the IP_xxx options so...
call nf_setsockopt: Search loaded netfilter modules for one that has registered IPT_SO_SET_REPLACE.
I think the last must have failed, so you get ENOPROTOOPT back (== Protocol not available)

Rand() function in threads

#include <pthread.h>
#ifndef __linux__
#include <windows.h>// to include the windows.h library//
#endif
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5
#include <sys/timeb.h>
void *PrintHello(void *threadid)
{
srand(time(NULL));
long tid,a;
tid = (long)threadid;
a=rand()%5;
printf("Hello World! It's me, thread #%ld!%ld\n", tid,a);
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t,a;
srand(time(NULL));
for(t=0; t<NUM_THREADS; t++){
a=rand()%5;
printf("In main: creating thread %ld,%ld\n", t,a);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
pthread_exit(NULL);
}
Alright I have this simple code and when I compile it inside the main() the random numbers
are different from one another but when i try to generate random numbers inside the threads, all the numbers that are produced are the same.
Try seeding from outside the threads. The problem is that you get the same seed for each thread

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