//SERVER SIDE SCRIPT for Deffie Hellman using sockets.
#include<stdio.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netdb.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#define MAX 80
#define PORT 43461
#define SA struct sockaddr
char* itoa(int value, char* str, int radix) {
static char dig[] =
"0123456789"
"abcdefghijklmnopqrstuvwxyz";
int n = 0, neg = 0;
unsigned int v;
char* p, *q;
char c;
if (radix == 10 && value < 0) {
value = -value;
neg = 1;
}
v = value;
do {
str[n++] = dig[v%radix];
v /= radix;
} while (v);
if (neg)
str[n++] = '-';
str[n] = '\0';
for (p = str, q = p + (n-1); p < q; ++p, --q)
c = *p, *p = *q, *q = c;
return str;
}
void func(int sockfd)
{
printf("hello"); //This statement is not being displayed and rest of the code not executed
char buff[MAX],uname[MAX],pass[MAX];
int n,clen,a1,a2,b2,val,key;
struct sockaddr_in cli;
clen=sizeof(cli);
xx:
//RECIEVING USERNAME
bzero(uname,MAX);
recvfrom(sockfd,uname,sizeof(buff),0,(SA *)&cli,&clen);
printf("Username recieved");
//RECIEVING PASSWORD
bzero(pass,MAX);
recvfrom(sockfd,pass,sizeof(buff),0,(SA *)&cli,&clen);
if(strcmp(uname,"admin") == 10 && strcmp(pass,"admin") == 10)
{
printf("Accepted");
//RECIEVING NUMBER FROM CLIENT
recvfrom(sockfd,buff,sizeof(buff),0,(SA *)&cli,&clen);
b2=atoi(buff);
printf("Recieved from client\n");
//GENERATING SERVER SIDE NUMBER
a1=(rand() % 19) + 1; // Random value selected by Server
a2=pow(7,a1);
a2=a2 % 11; // Server Generating value to be sent G:7 , P:11
//Sending the value-a2
bzero(uname,MAX);
itoa(a2,buff,10);
sendto(sockfd,buff,sizeof(buff),0,(SA *)&cli,clen);
printf("Server side number sent\n");
//GENERATING KEY AND THE DATA
key=pow(b2,a1);
key=key % 11; // G:7 , P:11
val=key*1024; // DATA: 7060
//Sending the data required
bzero(uname,MAX);
itoa(a1,buff,10);
sendto(sockfd,buff,sizeof(buff),0,(SA *)&cli,clen);
printf("Data sent \n");
}
else
{
printf("Incorrect Username-Password combination. Waiting for next try \n");
strcpy(buff,"wrong");
sendto(sockfd,buff,sizeof(buff),0,(SA *)&cli,clen);
goto xx;
}
}
int main()
{
int sockfd;
struct sockaddr_in servaddr;
sockfd=socket(AF_INET,SOCK_DGRAM,0);
if(sockfd==-1)
{
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(PORT);
if((bind(sockfd,(SA *)&servaddr,sizeof(servaddr)))!=0)
{
printf("socket bind failed...\n");
exit(0);
}
else
{
printf("%d",sockfd);// This value is displayed in the output screen
printf("Socket successfully binded..\n");}
func(sockfd);
close(sockfd);
}
执行脚本时,绑定成功完成,输出屏幕上显示相同的消息。但是没有执行函数调用func()。我没有得到函数调用的第一个语句 - &#39;你好&#39;在执行中。请建议此代码中所需的更改。
答案 0 :(得分:3)
如果bind()
成功,则会调用func()
。您没有看到输出的原因是因为stdout
通常是缓冲的,并且一旦内部缓冲区已满,它将刷新它。
将\n
添加到调试printf()
调用中,这将强制它刷新输出。
printf("hello\n");
同样,其他调试printf&#39>。您还可以使用fflush(stdout);
来刷新stdout
。
显然,您需要客户端代码,因为服务器正在您的代码中等待它。