Socket help with C++ - Windows Mobile Development and Hacking General

I'm developing a client PPC app on my Tilt that connects to a pre-existing server that runs on other applications just fine. So I'm sure the server is fine. I'm just doing something wrong in my client. I've tested the server with telnet and it works flawlessly too.
what should happen is:
1)Client connects.
2)Client sends a "password\r\n"
3)Server responds with "Authenticated ok"
4)Client sends "/status\r\n"
5)Server responds with
"Version: 1.5.7
Attached: False
Mode: None
Profile: C:\Profiles\afile.txt
Log: None
---"
If I do steps 1-3, my code works flawlessly. When I try to step 4-5 it doesnt work. actually step 4 doesnt hang at all. But when my client tries to recv step 5, it hangs. horribly.
What am I doing wrong in my 2nd send and receive that I'm not doing in my first?
Code:
int ConnectToServer(HWND hWnd)
{
// Declare and initialize variables.
int iResult;
WSADATA wsaData;
static char returnText[512];
SOCKET ConnectSocket;
struct sockaddr_in clientService;
int recvbuflen = DEFAULT_BUFLEN;
char recvbuf[DEFAULT_BUFLEN] = "";
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR) { sprintf(returnText,"WSAStartup failed with error: %d\n", iResult); return(1); }
// Create a SOCKET for connecting to server
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) { sprintf(returnText,"socket failed with error: %ld\n", WSAGetLastError()); WSACleanup();return(2); }
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr( "24.2.2.2" );
clientService.sin_port = htons( 3200 );
//MYSTEP 1
// Connect to server.
iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
if (iResult == SOCKET_ERROR) {sprintf(returnText,"connect failed with error: %d\n", WSAGetLastError() ); closesocket(ConnectSocket);WSACleanup();return(3); }
char outtext[50];
//MYSTEP 2
// Send password
strcpy (outtext,"mypassword\r\n");
iResult = send( ConnectSocket, outtext, (int)strlen(outtext)+1, 0 );
if (iResult == SOCKET_ERROR)
{ sprintf(returnText,"send() failed with error: %d\n", WSAGetLastError());closesocket(ConnectSocket);WSACleanup();return(4);
}
//MYSTEP 3
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
{
}
else if ( iResult == 0 )
{ strcpy(recvbuf, "connection was closed");}
else
{ sprintf(recvbuf,"recv failed: %d\n", WSAGetLastError()); }
mbstowcs(STATUS,recvbuf,strlen(recvbuf));
//MYSTEP 4
//send get status
strcpy (outtext,"/status\r\n");
iResult = send( ConnectSocket, outtext, (int)strlen(outtext)+1, 0 );
if (iResult == SOCKET_ERROR)
{
sprintf(returnText,"send() failed with error: %d\n", WSAGetLastError());closesocket(ConnectSocket);WSACleanup();return(4);
}
//MYSTEP 5
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
{
}
else if ( iResult == 0 )
{ strcpy(recvbuf, "connection was closed");}
else
{ sprintf(recvbuf,"recv failed: %d\n", WSAGetLastError()); }
mbstowcs(STATUS,recvbuf,strlen(recvbuf));
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
sprintf(returnText,"shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return(5);
}
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return(6);
}
with telnet here's my output.
Code:
Authenticated ok
Version: 1.5.7
Attached: False
Mode: None
Profile: C:\Profiles\afile.txt
Log: None
---
thanks xda!

Does the server get your (4)? You can launch Wireshark on PC to monitor the connection and find out.

that's good thinking! I installed wireshark and tried to figure out how to get it to listen on a port and tell me what was coming across, but this wireshark got the best of me this morning. I will try it this afternoon after I've had some coffee and read the directions.

kireol said:
that's good thinking! I installed wireshark and tried to figure out how to get it to listen on a port and tell me what was coming across, but this wireshark got the best of me this morning. I will try it this afternoon after I've had some coffee and read the directions.
Click to expand...
Click to collapse
In order to see the incoming data on a port, you could simply use netcat in place of your server. Very simple tool that does what what it's supposed to
A windows version does exist http://www.vulnwatch.org/netcat/nc111nt.zip

Wireshark doesn't "listen on a port". Your server must listen, and Wireshark will tell you everything that happens between server and client.

Does it hang in recv oder shutdown function?
Houser

Related

connect GPRS using RAS on Pocket PC 2005

Hi,
I 'm not able to establish GPRS connection using RasDial on PPC 2005 . It returns always error 633. That means:
"The port is already in use or is not configured for Remote Access dialout.� (See related Microsoft article: ErrMsg: Error 633: The Modem Is Not Installed or Configured...) "
But it works fine in PPC 2003. Does anyone gets RAS API run successfull on WM 5.0 ?
here is my code:
Code:
void ConnectGPRSDlg::connectViaRAS()
{
RASDIALPARAMS rasDialParam;
BOOL bPasswd,bRasEntryFound;
DWORD dwRes, dwSize, dwEntries, dw;
short n_attempts = 5;
HRASCONN g_rasConn = NULL;
CString szError,msg,szResult;
LPRASENTRYNAME lpRasEntry = NULL;
// structure init.
memset(&rasDialParam, 0, sizeof(RASDIALPARAMS));
rasDialParam.dwSize = sizeof (RASDIALPARAMS);
lpRasEntry = new RASENTRYNAME[20];
if(lpRasEntry == NULL)
{
szError.Format( _T("Out of memory") );
msg += szError;
m_editbox.SetWindowTextW(msg);
return;
}
lpRasEntry[0].dwSize = sizeof(RASENTRYNAME);
dwSize = sizeof(RASENTRYNAME) * 20;
dwRes = RasEnumEntries(NULL, NULL, lpRasEntry,
&dwSize, &dwEntries);
if (dwRes != 0)
{
szError.Format( _T("Error getting RAS entries %d"),dwRes );
msg += szError;
}
else
{
szError.Format( _T("got RAS %d entries\r\n "),dwEntries );
msg += szError;
for(dw = 0; dw < dwEntries; dw++)
{
if( 0 == _tcscmp( lpRasEntry[dw].szEntryName, L"T-Mobile Internet" ) )
{
bRasEntryFound = TRUE;
_tcscpy( rasDialParam.szEntryName, lpRasEntry[dw].szEntryName );
szError.Format( _T("found entry: %s\r\n "),lpRasEntry[dw].szEntryName );
msg += szError;
}
}
}
if (!bRasEntryFound) return;
//// connection name
//wcscpy(rasDialParam.szEntryName, _T("T-Mobile Internet") );
//
// parameters from connection structure
dwRes = RasGetEntryDialParams(NULL, &rasDialParam, &bPasswd);
if(dwRes != 0)
{
szResult.Format( _T("getting Dial Params error: %D \r\n") , dwRes );
szResult += szError;
}
else
{
szResult.Format(L"entryname: %s, number: %s \r\n", rasDialParam.szEntryName,rasDialParam.szPhoneNumber);
msg += szResult;
}
// szError.Format( _T("creat new Dial Params...\r\n"));
//msg += szError;
// // Copy in the user credetials.
//_tcscpy( rasDialParam.szEntryName, _T("T-Mobile Internet") );
//_tcscpy( rasDialParam.szUserName, _T("t-mobile") );
//_tcscpy( rasDialParam.szPassword, _T("pwd") );
//_tcscpy( rasDialParam.szPhoneNumber, _T("*99#") );
//_tcscpy( rasDialParam.szCallbackNumber, _T("") );
szResult.Format(L"entryname: %s, number: %s \r\n", rasDialParam.szEntryName,rasDialParam.szPhoneNumber);
msg += szResult;
m_editbox.SetWindowTextW(msg);
do{
// if connection fails, hangup and retry... for 5 attemps
DWORD dwResult = RasDial(NULL,NULL,&rasDialParam,0,NULL,&g_rasConn);
Sleep(2000);
if ( dwResult != 0)
{
szError.Format(L"RAS error: %d \r\n", dwResult);
msg += szError;
m_editbox.SetWindowTextW(msg);
RasHangUp(g_rasConn);
g_rasConn = NULL;
n_attempts--;
}
else {
break;
}
}
while(n_attempts);
if(n_attempts == 0)
{
//AddDebugInfo( L"Can't connect GPRS" );
}
else
{
RASCONNSTATUS rasConStatus;
memset(&rasConStatus, 0, sizeof(RASCONNSTATUS));
rasConStatus.dwSize = sizeof(RASCONNSTATUS);
RasGetConnectStatus(g_rasConn, &rasConStatus);
if(rasConStatus.dwError == 0) {
szResult.Format( L"GPRS connected \r\n" );
msg += szResult;
}
else
{
szResult.Format(L"Ras connect status: %s \r\n", rasConStatus.dwError);
msg += szResult;
}
}
m_editbox.SetWindowTextW(msg);
return;
}

Windows Mobile SendSMS

I'm trying to send out a generic message using SENDSMS function in Windows Mobile Sample Code but I am unsuccessful. Here is a copy of the code
Code:
// ***************************************************************************
// Function Name: SendSMS
//
// Purpose: Send an SMS Message
//
// Arguments: none
//
// Return Values: none
//
// Description:
// Called after everything has been set up, this function merely opens an
// SMS_HANDLE and tries to send the SMS Message.
void SendSMS(BOOL bSendConfirmation, BOOL bUseDefaultSMSC, LPCTSTR lpszSMSC, LPCTSTR lpszRecipient, LPCTSTR lpszMessage)
{
SMS_HANDLE smshHandle;
SMS_ADDRESS smsaSource;
SMS_ADDRESS smsaDestination;
TEXT_PROVIDER_SPECIFIC_DATA tpsd;
SMS_MESSAGE_ID smsmidMessageID;
// try to open an SMS Handle
if(FAILED(SmsOpen(SMS_MSGTYPE_TEXT, SMS_MODE_SEND, &smshHandle, NULL)))
{
MessageBox(NULL,
(LPCTSTR)LoadString(ghInstance, IDS_ERROR_SMSOPEN, 0, 0),
(LPCTSTR)LoadString(ghInstance, IDS_CAPTION_ERROR, 0, 0),
MB_OK | MB_ICONERROR);
return;
}
// Create the source address
if(!bUseDefaultSMSC)
{
smsaSource.smsatAddressType = SMSAT_INTERNATIONAL;
_tcsncpy(smsaSource.ptsAddress, lpszSMSC, SMS_MAX_ADDRESS_LENGTH);
}
// Create the destination address
smsaDestination.smsatAddressType = SMSAT_INTERNATIONAL;
_tcsncpy(smsaDestination.ptsAddress, lpszRecipient, SMS_MAX_ADDRESS_LENGTH);
// Set up provider specific data
memset(&tpsd, 0, sizeof(tpsd));
tpsd.dwMessageOptions = bSendConfirmation ? PS_MESSAGE_OPTION_STATUSREPORT : PS_MESSAGE_OPTION_NONE;
tpsd.psMessageClass = PS_MESSAGE_CLASS1;
tpsd.psReplaceOption = PSRO_NONE;
tpsd.dwHeaderDataSize = 0;
// Send the message, indicating success or failure
if(SUCCEEDED(SmsSendMessage(smshHandle, ((bUseDefaultSMSC) ? NULL : &smsaSource),
&smsaDestination, NULL, (PBYTE) lpszMessage,
_tcslen(lpszMessage) * sizeof(TCHAR), (PBYTE) &tpsd,
sizeof(TEXT_PROVIDER_SPECIFIC_DATA), SMSDE_OPTIMAL,
SMS_OPTION_DELIVERY_NONE, &smsmidMessageID)))
{
MessageBox(NULL,
(LPCTSTR)LoadString(ghInstance, IDS_SMSSENT, 0, 0),
(LPCTSTR)LoadString(ghInstance, IDS_CAPTION_SUCCESS, 0, 0),
MB_OK);
}
else
{
MessageBox(NULL,
(LPCTSTR)LoadString(ghInstance, IDS_ERROR_SMSSEND, 0, 0),
(LPCTSTR)LoadString(ghInstance, IDS_CAPTION_ERROR, 0, 0),
MB_OK | MB_ICONERROR);
}
// clean up
VERIFY(SUCCEEDED(SmsClose(smshHandle)));
}
Again, I am trying to explicitly specify the recipient and the message being sent which are variables LPCTSTR lpszRecipient and LPCTSTR lpszMessage. Every time I assign them a string value, I get an error. Does anybody know a solution?
Not sure
Not too sure what you are trying to achieve here, as Vijay already has an SMSSend app, which is command line driven and works a treat. Would hate for you to reinvent the wheel - check his tools out: http://www.vijay555.com/?Releases:VJPhoneTools

Porting / Converting Windows .exe to Windows Mobile .cab/exe

Ive looked but havnt managed to find a windows .exe convertor to windows mobile. Ive found a program which can shutdown remote pcs on the same network and want to port it to my windows mobile (6.1) - HTC Kaiser.
Ive installed the visual studio and the sdk aswell as the 2.0 mobile framework.
Any ideas where to go from here?
Thanks
Source code to Windows App...
Code:
//-----------------------------------------------------------
// Remote Shutdown v1.0 Console Mode
// Copyright (C) 2002, MATCODE Software
// http://www.matcode.com
// Author: Vitaly Evseenko
//-----------------------------------------------------------
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#pragma hdrstop
int RemoteShutdown(LPSTR lpMachineName, LPSTR lpMessage,
DWORD dwTimeout, BOOL bForceAppsClosed,
BOOL bRebootAfterShutdown )
{
HANDLE hToken;
TOKEN_PRIVILEGES TokenPrivileges;
OpenProcessToken( GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken ) ;
LookupPrivilegeValue( NULL, SE_REMOTE_SHUTDOWN_NAME, &(TokenPrivileges.Privileges[0].Luid));
TokenPrivileges.PrivilegeCount = 1;
TokenPrivileges.Privileges[0].Attributes = 2;
AdjustTokenPrivileges( hToken, FALSE, &TokenPrivileges,
sizeof(TOKEN_PRIVILEGES), NULL, NULL );
if(!InitiateSystemShutdown(
lpMachineName, // name of computer to shut down
lpMessage, // address of message to display
dwTimeout, // time to display dialog box
bForceAppsClosed, // force applications with unsaved changes flag
bRebootAfterShutdown ))
{
return GetLastError();
}
return 0;
}
void OutUsage(void)
{
printf("\nUsage: RSD-CON ComputerName [Message] [/tnn] [/f] [/s]\n");
printf("\tComputerName - remote computer name\n");
printf("\tMessage - specify message to display\n");
printf("\t/t - time to display message (nn seconds)\n");
printf("\t/f - do not force applications with unsaved changes flag\n");
printf("\t/s - the computer is to shut down.\n");
printf("Example: RSD-CON PC_LARRY This computer will be restarted now. /t20\n");
}
void main( int argc, char *argv[] )
{
char szMachineName[100];
char szMessage[200];
DWORD dwTimeout;
BOOL bForceAppsClosed;
BOOL bRebootAfterShutdown;
int i, Err;
printf("Remote Shutdown v1.0, Console\n");
printf("Copyright (C) 2002, MATCODE Software\n");
printf("http://www.matcode.com\n");
if (GetVersion() & 0x80000000) // Not Windows NT/2000/XP
{
printf("\n\tThis is a Windows NT/2000/XP application.\n"
"This program will not work on Windows 95/98/ME !\n");
return;
}
if(argc<2)
{
OutUsage();
return;
}
strcpy(szMachineName, argv[1]);
dwTimeout = 0;
bForceAppsClosed = TRUE;
bRebootAfterShutdown = TRUE;
szMessage[0] = '\0';
for( i = 2; i < argc; i++ )
{
// if not started with / then message ;-)
if( argv[i][0] != '/')
{
strcat(szMessage, argv[i]);
strcat(szMessage, " ");
continue;
}
// parse option type
if(argv[i][1]=='t' || argv[i][1]=='T')
{
dwTimeout = atol(&argv[i][2]);
}
else if(argv[i][1]=='f' || argv[i][1]=='F')
{
bForceAppsClosed = FALSE;
}
else if(argv[i][1]=='s' || argv[i][1]=='S')
{
bRebootAfterShutdown = FALSE;
}
}
if (dwTimeout == 0 && szMessage[0])
{
dwTimeout = 5;
}
Err = RemoteShutdown(szMachineName, szMessage,
dwTimeout, bForceAppsClosed,
bRebootAfterShutdown );
if(Err)
{
LPSTR lpstErr = "\0";
if(Err == 53)
{
lpstErr = "The network path was not found.\n"
"Invalid computer name or is not Windows NT/2000/XP machine.\n";
}
else if(Err == 5)
{
lpstErr = "Access is denied. You have no administrative rights on the specified computer.\n";
}
printf("\nUnable to shutdown computer %s, Error: %d.\n%s",
szMachineName, Err, lpstErr);
OutUsage();
}
else
{
printf("\nComputer %s is shut down.\n", szMachineName);
}
}
Hi
This is not that easy. While a lot API calls exists in both Windows and WinMo I doubt that the ones used in this tool are available.
cool this is one development many people is waiting for, especially me
wish you good luck
Hi..interesting topics anyway.
As long as the APIs used in Windows app are also available in Windows Mobile, that will be possible IMO.
The one I'm sure about, the Windows Mobile apps built using .net, will also be available to run in Windows

Problem creating a windows socket for bluetooth

When I try to create a socket in a C++ program I get an INVALID_SOCKET.
I've used the code shown below and the error code from the socket function
is 10047, which according to MSDN is WSAEAFNOSUPPORT (Address family not supported by protocol family)
I've used the exact same piece of code on a HTC Touch Diamond 2 and it works. The problem only appears on the HD2.
Any help would be appreciated.
Thanks,
TJ
// Initialize WSA
WORD wVersionRequested = MAKEWORD(2,2);
if (WSAStartup(wVersionRequested, &m_wsaData) != 0)
{
Log(L"Failed to start WSA");
return false;
}
if ( LOBYTE( m_wsaData.wVersion ) != 2 ||
HIBYTE( m_wsaData.wVersion ) != 2 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
Log(L"Wrong winsock version");
WSACleanup( );
return false;
}
// Create the listening socket
m_listenSocket = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
if (INVALID_SOCKET == m_listenSocket)
{
std::stringstream errorMessage;
errorMessage << "ERROR: Could not create socket.\n Error code: " << GetLastError();
Log(A2W(errorMessage.str().c_str()));
return false;
}

Communicating with Nexus-4 using libusb in firmware update mode

Hi,
I am trying to develop a simple program to communicate with the Nexus-4 bootloader in firmware update mode.
Nexus -4 has three usb interfaces. Interface-1 has two 2 endpoints - 2 and 131.
I wrote a program to write the command, get-device-info, through endpoint 2 and listen at endpoint 131 for the reply.
(I tried all permutations of interfaces and endpoints!).
The program successfully writes the command to the device but nothing is read from the device. The following is the program.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <libusb-1.0/libusb.h>
#define INTERFACE 1
#define EP_OUT 2
#define EP_IN 131
int main() {
libusb_device **devs; // retrieve a list of devices
libusb_device_handle *dev_handle; // device handler
libusb_context *ctx = NULL; //a libusb session
int r, r2, i;
ssize_t cnt; //holding number of devices in list
unsigned char data[30],read_data[512]; //data to write
data[0]=0x7e;data[1]=0x00;data[2]=0x78;data[3]=0xf0;data[4]=0x7e; // get-device-info command in HLDC format
int actual,read_actual;
r = libusb_init(&ctx);
if(r < 0) {
printf("Init Error\n");
return 1;
}
libusb_set_debug(ctx, 3);
cnt = libusb_get_device_list(ctx, &devs); //get the list of devices
if(cnt < 0) {
printf("Get Device Error\n");
return 1;
}
printf("%d Devices in list\n",(int)cnt);
dev_handle = libusb_open_device_with_vid_pid(ctx, 4100, 25371); //these are vendorID and productID I found for Nexus-4 firmware update
if(dev_handle == NULL)
printf("Cannot open device\n");
else
printf("Device opened\n");
libusb_free_device_list(devs, 0); //free the device list
if(libusb_kernel_driver_active(dev_handle, INTERFACE) == 1) { //find out if kernel driver is attached
printf("Kernel Driver Active\n");
if(libusb_detach_kernel_driver(dev_handle, INTERFACE) == 0) //detach it
printf("Kernel Driver Detached!\n");
}
r = libusb_claim_interface(dev_handle, INTERFACE); //claim interface 1 Nexus-5/4 FUM
if(r < 0) {
printf("Cannot Claim Interface\n");
printf("%s\n",libusb_error_name(r));
return 1;
}
printf("Claimed Interface\n");
printf("Data to be send -> %s\n",data); //just to see the data that we are writing
printf("Writing Data...\n");
r = libusb_bulk_transfer(dev_handle, (EP_OUT | LIBUSB_ENDPOINT_OUT), data, 5, &actual, 0);
if(r == 0 && actual == 5){ //we wrote successfully 5 bytes to the device
printf("Writing Successful!\n");
printf("Waiting to read from device!\n");
r2 = libusb_bulk_transfer(dev_handle, (EP_IN | LIBUSB_ENDPOINT_IN), read_data, 512, &read_actual, 5000);
if (r2 >=0){
if (read_actual > 0){
printf("Data received by bulk transfer\n");
printf("Data is ");
for (i=0; i<read_actual; i++)
printf("%x ",read_data[i]);
printf("\n");
}
else{
printf(stderr, "No data received in bulk transfer (%d)\n", r2);
return -1;
}
}
else{
fprintf(stderr, "Error receiving data via bulk transfer %d\n", r2);
return r2;
}
}
else
printf("Write Error\n");
r = libusb_release_interface(dev_handle, INTERFACE); //release the claimed interface
if(r!=0) {
printf("Cannot Release Interface\n");
return 1;
}
printf("Released Interface\n");
libusb_close(dev_handle);
libusb_exit(ctx);
return 0;
}
And when I run the program, I get the following output:
----------------------------------------------------------------------
10 Devices in list
Device opened
Kernel Driver Active
Kernel Driver Detached!
Claimed Interface
Data to be send -> ~
Writing Data...
Writing Successful!
Waiting to read from device!
Error receiving data via bulk transfer -7
---------------------------------------------------------------------
Can someone tell me what am I doing wrong in the program?

Categories

Resources